date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,410,708,734,000 |
I believe that something strange is going on with my swap / hardware / drivers.
I'm trying to increase the swap size by swapoff, lvresize, then swapon again.
When I did swapoff /dev/swapdev, the command took 8mins 19seconds to move about 3.5GB of swapped pages into memory.
I ensured that my free RAM was greater than the swap usage before running swapoff, and this stayed true while it was running.
I have a Intel Core i5 laptop with SSD HDD. The processor was at less than 10% before swapoff, and when I checked in, swapoff was using 70%+ CPU.
There was nothing interesting in the journal the whole time.
Here's approximately how long I'd expect it to take to shunt 3.5G from disk to memory:
$ time dd if=/dev/urandom of=/tmp/del bs=1M count=3500
3500+0 records in
3500+0 records out
3670016000 bytes (3.7 GB, 3.4 GiB) copied, 23.7288 s, 155 MB/s
real 0m24.789s
user 0m0.000s
sys 0m22.743s
I'm running Linux svelte 4.9.53-1-MANJARO #1 SMP PREEMPT Thu Oct 5 15:11:15 UTC 2017 x86_64 GNU/Linux
Any reason that the command would take so long? This could be part of a larger issue, but this is the first thing that I can definitively point at which looks strange.
|
You're missing what swapoff really does.
Retiring swap space on a running machine, which is swapping, is extremely complex. 3.5G in 8min is likely very fast + is working as expected.
Running swapoff doesn't just simply move code off disk into memory.
Once you're swapping... well... you're swapping, which means your OS is starved for memory + you have disk i/o to your swap device + disk i/o to your other file systems + maybe even the OOM (out of memory killer) starting to run + then process thrash of OOM'ed processes restarting, if watchdogs or systemd auto restarts are involved.
If your system is swapping, that means swapping is the only thing keeping your system alive.
If you kill swap space, then your system can't use swap space anymore, so now your OS has to load code of normal filesystems + evict code when memory is exhausted + then rather then pulling code off fast swap space via optimized, raw disk reads, all your code has to come off normal filesystems, with directory walks. This is far more resource intensive, than pulling from swap space.
When you do a swapoff on a system that's swapping... usually you'll end up in a situation where this process will take hours + sometimes machines will crash.
If you have to retire a swap device for some reason, best to first create a secondary, filesystem based swap space + do a swapon for this new swap space, then do your swapoff on the old swap device.
If you take this approach, your system will always survive.
| Why is swapoff so slow? [duplicate] |
1,410,708,734,000 |
If I want to set a capability (capabilities(7)), such as CAP_NET_BIND_SERVICE, on an executable file and that file is a script, do I have to set the capability (setcap(8)) on the interpreter starting that script or is it sufficient to set it on the script file itself?
Note: the question concerns Scientific Linux 6.1 in particular, but I think it can be answered generically.
|
Setting capability on the script will not be effective. It's the similar situation as not working setuid bit on script. Similar as in the latter case it's the implementation of how execve handles shebang and the security reasoning behind it (for details see: Allow setuid on shell scripts).
I think you have these options
set the capabilities on interpreter itself (actually rather a copy of it)
you have a problem here that anybody who is able to execute it will run with those elevated capabilities (be able to execute some arbitrary script or start it interactively)
write a wrapper executable which will have a hardcoded logic to execute your script, and set desired capabilities on this executable
make sure that nobody is able to modify nor remove / replace the script
still by doing chroot one might missuse such wrapper
In both cases you would have to make sure capabilities set will survive execve by setting inheritable flag. You might also use pam_cap distributed with libcap usually, to actually activate desired capabilities by configuration only for selected users.
And in general you want to make sure nobody is able to modify behavior of your interpreter by changing environment eg. PYTHON_PATH or something similar.
| Capabilities for a script on Linux |
1,410,708,734,000 |
I have a server process and a client process running on the same Linux machine.
Sometimes when I kill -9 the client, I see with tcpdump that a FIN, ACK message is sent. Of course the dead client couldn't have done it because he's dead brutally with SIGKILL. So I guess Linux OS handles the connection closing.
Sometimes I don't see any connection-close-handling and the connection stays “ESTABLISHED” (by netstat).
I always see a connection being closed in Linux ubuntu 4.4.0-53-generic.
Sometimes I see a connection being closed in Linux 3.13.11 (pure kernel, not Ubuntu).
My questions are:
Does Linux handles closing connections?
1.1 In SIGKILL?
1.2. When application closed properly, but doesn't call close()?
Did this functionality change between kernel versions 3.13.11 and 4.4.0 ? Does Ubuntu has anything with it?
What if those two processes weren't on the same Linux machine: would it behave the same?
Why does the connection sometimes stay “ESTABLISHED”?
I'm aware of TCP keepalive socket options. If Linux really handles closing the connection. Why do they exist? Only if the FIN, ACK packet drops?
|
A broad question. Perhaps someone can weigh in on your question about the kernel TCP stack between specific kernel versions.
A couple of general answers:
From the client side
In the event of a SIGKILL signal, the kernel terminates program execution, and among other things, closes the process's open file descriptors. TCP sockets are handled a bit differently by the kernel than regular files, in that they need to be flushed and go through the TCP shudown process.
The difference in an immediate 'FIN, ACK' from the client and a longer socket shut down could depend on what state the client TCP connection was in when the client application was terminated. But generally the kernel will close the application's open sockets.
From the server side
A server does not always know when a client disconnects. The most reliable way to determine if a client has hung up is to attempt a read from the socket which returns an EOF.
TCP is designed to be resilient to connection latency and intermittent failures. This also translates to some challenges reliably detecting disconnections in the event the FIN, ACK 4 way disconnection handshaking does not occur.
Summary
What you might be seeing upon a kill -9 of the client is the server going into the CLOSE_WAIT of the TCP state, where it is waiting for a TCP timeout. This can take a while. Even though the client is gone, if the kernel did not handle the TCP disconnection handshaking, the server will have to timeout.
If I remember this can take several additional seconds and is likely why you still see ESTABLISHED due to running both the client and server on the same host.
| When/how does Linux decides to close a socket on application kill? |
1,410,708,734,000 |
I am trying to overclock my machine. All the changes are made on the BIOS level, but then one needs to check all the temperatures, voltages, etc and test the stability of the overclock. Most tutorials (if not all) are written for Windows. What would be Linux alternatives for:
CPU-Z: to display all the CPU information, including Core Speed, Core Voltage, current multiplier, etc.
HWMonitor: check fan speed and core temperatures
Prime95: stress testing with results validation
Also I would like to be able to monitor VTT and NB voltages (see a short explanation of all voltages) for Intel processors (I have a Q9450) - I haven't actually found a Windows program that does it yet.
|
For CPU-Z I can't really say (/proc/cpuinfo doesn't give core speed, multiplier etc...).
For hardware monitoring the sensors command (part of the lm_sensors package) should work; it doesn't have a GUI per se, however.
Finally, the stresslinux distro has many stress-testing utilities.
stresslinux makes use of some utitlities available on the net like: stress, cpuburn, hddtemp, lm_sensors ...
stresslinux is dedicated to users who want to test their system(s) entirely on high load and monitoring the health.
Stresslinux is for people (system builders, overclockers) who want to test their hardware under high load and monitor stability and thermal environment.
| Overclocking tools in Linux |
1,410,708,734,000 |
I have a self-written interface tun0 (TUN/TAP based) that outputs what it receives.
I need all traffic of the system to flow through this interface.
The role of the interface is:
To figure out packets likely to be censored and tunnel them.
Pass all other traffic untouched.
As you guess I am trying to build an anticensorship tool.
Decision about tunneling must be taken inside tun0 process
because only there we may use trusted DNS.
I need your help to show me how to make all traffic flow through a self-written interface tun0. If tun0 needs changes I ask you to provide such changes.
Below is how I tried to make all traffic go through tun0 and failed (pings fail).
Compiling
gcc tun0.c
sudo ./a.out
Configuring
sudo ip addr add 10.0.0.1/24 dev tun0
create table John
$ cat /etc/iproute2/rt_tables
#
# reserved values
#
255 local
254 main
253 default
0 unspec
#
# local
#
#1 inr.ruhep
200 John
Order is important:
sudo ip rule add from all lookup John
sudo ip route add default dev tun0 table John
sudo ip rule add iif tun0 lookup main priority 500
$ ip rule
0: from all lookup local
500: from all iif tun0 lookup main
32765: from all lookup John
32766: from all lookup main
35000: from all lookup default
Troubleshooting
sudo tcpdump -i wlp2s0 -qtln icmp and then ping -I tun0 8.8.8.8 shows no packets captured, it means no packets are transmitted from tun0 to wlp2s0 via iif tun0 lookup main rule.
When I replaced tun0 with lo everywhere then it worked for me.
Also Tried
Turning off reverse path filtering, rp_filter=0 in /etc/sysctl.conf
Answer Troubleshooting
iptables -I FORWARD -j LOG --log-prefix "filter/FORWARD "
iptables -t nat -I OUTPUT -j LOG --log-prefix "nat/OUTPUT "
iptables -t nat -I PREROUTING -j LOG --log-prefix "nat/PREROUTING "
iptables -t nat -I POSTROUTING -j LOG --log-prefix "nat/POSTROUTNG "
tail -f /var/log/syslog
Modified sources from answer are also here.
|
So in your configuration, all the packets you try to send to the network initially originating from 10.0.0.1 (because they are going through tun0 interface and its local address is 10.0.0.1). You capture the packets, everything is fine so far.
Now, tun0 sends the packets further. Source address is 10.0.0.1 and you want the packets to leave through a different interface (wlp2s0 in your case). That's routing so let's enable routing first:
sysctl -w net.ipv4.ip_forward=1
After that, if you'll look at tcpdump for wlp2s0 you can notice the packets leave with source address 10.0.0.1 and not with the source address of the wlan interface (what you would expect I guess). So we need to change the source address and it's called source NAT. In linux it's easy with help of netfilter/iptables:
iptables -t nat -A POSTROUTING -o wlp2s0 -s 10.0.0.1 -j MASQUERADE
Please also check that your FORWARD chain has ACCEPT policy or you would need to allow forwarding with something like:
iptables -A FORWARD -i tun0 -o wlp2s0 -s 10.0.0.1 -j ACCEPT
iptables -A FORWARD -i wlp2s0 -o tun0 -d 10.0.0.1 -j ACCEPT
Everything should work now: linux kernel does the routing, it's moving packets from tun0 interface to wlp2s0. netfilter should change the source IP 10.0.0.1 to your wlp2s0 interface assigned address for output packets. It memorizes all the connections and when the reply packets go back (if they) it changes the destination address of the wlp2s0 interface assigned address to 10.0.0.1 (the "conntrack" feature).
Well, it should but it doesn't. It seems, netfilter gets confused with this complicated routing configuration and the fact that the same packet first goes through the OUTPUT chain and then being routed and comes to PREROUTING chain. At least on by Debian 8 box it doesn't work.
The best way to troubleshoot netfilter is the TRACE feature:
modprobe ipt_LOG
iptables -t raw -A OUTPUT -p icmp -j TRACE
iptables -t raw -A PREROUTING -p icmp -j TRACE
I only enable tracing for ICMP packets, you may use other filter to debug.
It will show what tables and chains the packet goes through. And I can see that the packet goes no further the FORWARD chain (and it's not being caught by the nat/POSTROUTING chain that actually does SNAT).
Below are several approaches to make this work.
APPROACH #1
The best way to un-confuse netfilter is to change the source IP address of packets in tun0.c application. It's also the most natural way.
We need to change 10.0.0.1 to 10.0.0.2 on the way outwards and 10.0.0.2 to 10.0.0.1 on the way back.
I've modified tun0.c with source address change code. Here is the new file and here is patchfile for your tun0.c. Changes to IP header also involve checksum correction, so I took some code from OpenVPN project.
Here is the full list of commands I execute after a clean reboot and tun0_changeip.c launch:
ifconfig tun0 inet 10.0.0.1/30 up
sysctl -w net.ipv4.ip_forward=1
ip route add default dev tun0 table John
ip rule add from all lookup John
ip rule add from 10.0.0.2 lookup main priority 500
iptables -t nat -A POSTROUTING -o wlp2s0 -s 10.0.0.2 -j MASQUERADE
Please note that you don't need to turn off the reverse path filtering in that case, because everything is legal - tun0 only receives and sends packets that belong to its subnet. Also you can do a source-based routing instead of interface-based.
APPROACH #2
It's possible to do SNAT before the packet reach tun0 interface. It's not very correct though. You will definitely need to turn off the reverse path filtering in this case:
sysctl -w net.ipv4.conf.tun0.rp_filter=0
# It won't work without also changing the "all" value
sysctl -w net.ipv4.conf.all.rp_filter=0
Now, do SNAT:
iptables -t nat -A POSTROUTING -o tun0 -s 10.0.0.1 -j SNAT --to-source ip.address.of.your.wlan.interface
Here we change the source address just before the packets reach the tun0 device. tun0.c code resend these packets "as is" (with changed source address) and they are successfully routed through wlan interface.
But you might have a dynamic IP on wlan interface and want to use MASQUERADE (in order to not specify the interface address explicitly). Here is how you can make use of MASQUERADE:
iptables -t nat -A POSTROUTING -o tun0 -s 10.0.0.1 -j SNAT --to-source 10.0.55.1
iptables -t nat -A POSTROUTING -o wlp2s0 -s 10.0.55.1 -j MASQUERADE
Please note the "10.0.55.1" IP address - it's different. You can use any IP here, it doesn't matter. The packets reach nat/POSTROUTING chain on wlp2s0 interface if we change the source IP before. And now it's not dependent on a static IP for wlan interface.
APPROACH #3
You can also use fwmark. That way you don't need SNAT but you'll capture only outgoing packets:
First we need to disable reverse path filtering for tun0 because it will forward packets that belong to another network:
sysctl -w net.ipv4.conf.tun0.rp_filter=0
# It won't work without also changing the "all" value
sysctl -w net.ipv4.conf.all.rp_filter=0
Now let's alter the routing rules a bit:
# Delete old rules
ip rule del iif tun0 lookup main
ip rule del from all lookup John
# Packets will start going from wlan interface so they will have source address of it
iptables -t mangle -A OUTPUT -o wlp2s0 -j MARK --set-mark 1
ip rule add fwmark 0x1 lookup John
That's another "hack" for routing and netfilter that works on my Debian 8 box, but still I recommend to take the first approach as it's more natural and doesn't use any hacks.
You may also consider to build your application as a transparent proxy. I think it would be much easier instead of analyzing packets from tun device.
| How To Make All Traffic To Go Through One Interface In Linux |
1,410,708,734,000 |
My computer is running macOS 10.12.3 and I am using the system-installed grep utility with version 2.5.1-FreeBSD.
These are the outputs I get when testing various regexes:
But if I run these using GNU grep (version 2.25) I get the following:
GNU's grep looks correct to me and BSD's is incorrect, no? Why do they differ? I don't understand why BSD's grep is matching the "a" when the regex specifies that it must follow the beginning of the line.
|
I think this might be a bug in FreeBSD's grep. There's a bug report with similar issues.
| Why does this BSD grep result differ from GNU grep? |
1,410,708,734,000 |
I want to be notified when a specific filename is created. I'm looking at inotify. The IN_CREATE flag is available for monitoring a directory for any changes within it, but I'd prefer not to monitor the entire directory since there may be a good deal of activity in that directory besides the file I'm interested in. Can this be done?
|
You cannot have the kernel only inform you of a change to a certain path. The reasons are a bit subtle:
In Linux, a file object exists independently of any name(s) it may have. Files' names are actually attributes of their containing directory, and a single file may be called by multiple names (see, hardlinking).
The kernel has to have something to attach inotify objects to; it cannot attach an object to a pathname since a pathname isn't a real filesystem object; you have to attach to the parent directory or the file that path describes. But you can't attach to the file, because you're watching to see if a file with a given name is created, not changes to a given file.
Theoretically, the kernel could implement an API that allows you to select events for a given pathname when adding a watch to a directory, much in the same way it allows you to select types of events. This would bloat the API, and the kernel would in the end be processing the same data and doing the same string comparison you would be doing in userspace.
Is there a noticeable performance hit to placing a watch on a very active directory? I'm not sure how active you mean; tens of files a second, hundreds, millions?
In any case, I would avoid access: it's always going to be racey. A file could be created and removed between calls to access, and calling access in a very tight loop is going to be slow, and is the kind of problem inotify was designed to solve.
| Can inotify be used to watch for a specific file to be created without monitoring the entire directory? |
1,410,708,734,000 |
I have a USB barcode scanner at /dev/input/event0 (/dev/input/by-id/usb-Metrologic_Metrologic_Scanner-event-kbd), and scanning a barcode causes it to send keypress events. I'm capturing these keypresses using the libdevinput Ruby library, which works great. The issue is that each barcode is also entered as a username, and subsequently a password on the Raspberry Pi, causing lots of failed login attempts. (The Raspberry Pi will be headless, and inside a microwave.)
How can I stop Linux from seeing the barcode scanner as an input device, and have my program be the sole event consumer? Or is there a different, better solution?
|
I found out that I need to send an EVIOCGRAB ioctl to the device, which grabs it for exclusive use.
Here's how to do it in Ruby:
#!/usr/bin/env ruby
BARCODE_SCANNER = "/dev/input/by-id/usb-Metrologic_Metrologic_Scanner-event-kbd"
require 'rubygems'
require 'libdevinput'
require 'ffi'
require 'ffi/tools/const_generator'
# We need access to the file
DevInput.class_eval { attr_reader :dev }
# Look up value of EVIOCGRAB constant
cg = FFI::ConstGenerator.new('input') do |gen|
gen.include('linux/input.h')
gen.const(:EVIOCGRAB, '%u', '(unsigned)')
end
EVIOCGRAB = cg['EVIOCGRAB'].to_i
scanner = DevInput.new(BARCODE_SCANNER)
# Send EVIOCGRAB to scanner, which grabs it for exclusive use by our process
scanner.dev.ioctl(EVIOCGRAB, 1)
puts "Waiting for events..."
scanner.each do |event|
# Ignore everything except key press events
next unless event.type == 1 && event.value == 1
puts "Key: #{event.code_str}"
end
Note: You'll need to install the libdevinput gem, ffi, and Linux headers. If you are using a Linux version between 3.2.0 and 3.6.11, you can replace the FFI::ConstGenerator part with EVIOCGRAB = 1074021776, and then you don't need ffi or Linux headers.
| Can I stop Linux from listening to a USB input device as a keyboard, but still capture events with a program? |
1,410,708,734,000 |
getrlimit(2) has the following definition
in the man pages:
RLIMIT_AS
The maximum size of the process's virtual memory (address space) in bytes. This limit affects calls to brk(2), mmap(2) and mremap(2), which fail with the error ENOMEM upon exceeding this limit. Also automatic stack expansion will fail (and generate a SIGSEGV that kills the process if no alternate stack has been made available via sigaltstack(2)). Since the value is a long, on machines with a 32-bit long either this limit is at most 2 GiB, or this resource is unlimited.
What is meant by "automatic stack expansion" here? Does the stack in a Linux/UNIX environment grow as needed? If yes, what's the exact mechanism?
|
Yes stacks grow dynamically. The stack is in the top of the memory growing downwards towards the heap.
--------------
| Stack |
--------------
| Free memory|
--------------
| Heap |
--------------
.
.
The heap grows upwards (whenever you do malloc) and the stack grows downwards as and when new functions are called. The heap is present just above the BSS section of the program. Which means the size of your program and the way it allcates memory in heap also affect the maximum stack size for that process. Usually the stack size is unlimited (till heap and stack areas meet and/or overwrite which will give a stack overflow and SIGSEGV :-)
This is only for the user processes, The kernel stack is fixed always (usually 8KB)
| What is "automatic stack expansion"? |
1,410,708,734,000 |
I would like to became an Expert of managing KVM on debian squeeze.
I still use virt-manager. Yes, it is easy and quiet safe and quick for me.
I tried a lot of web based management UI and non of them was good enough like virt-manager.
You know, I'm one of those guys, who used to have VMware before, where 90% of managing is clicking.
My questions :
1) Are there any CLI "interactive" utility like mc (midnight commander) or something how to control KVM ? (ON/OFF VMs, increasing memmory, reseting VMs, adding virtual hardware, adding new disks, and so on...)
2) Could you recommend me some Web based management UI for KVM on debian squeeze?
Did you see VMware server 2? There is web management. I know it was slow, but it is fine, when you are somewhere without terminal. (for example on android with web browser)
I tried a lots of them, but nothing i tried was working.
3) What tutorials could you recommend me to improve myself in commands to control virsh, kvm and so on? Google is full of low quality tutorials with mistakes and misunderstandings. I need something for debian.
4) Could you recommend me some tutorials how to improve performance for KVM? Google is full of a lot of tutorials, but I need some recommendations from real experts, who knows, how to improve it.
5) How to improve security of KVM? Can solve this problem some Web based UI? (for example accounting, user management ?)
|
Q1&2
For web-based KVM manager, you can try Proxmox. Instruction for Debian Squeeze is here.
It has command-line tools, but not text-based -- menu-driven.
Q3
You should setup a small environment and try it out. Then set out a goal and implement it.
Q4
There is no accurate answer/tutorial for this. How tunable your KVM server/client is really depends on how many resources (cpu/ram/storage) are available.
Q5
Again, this depends on your environment and it is multi-layers/devices, e.g. routers, firewall, ip-tables, password policy, access policy, etc. I am not aware of a single GUI, web-based or not, that can handle all of that including the KVM. (OK, there is cloudmin, but I have no experience with that at all)
| KVM - Which Web Based management to use? |
1,410,708,734,000 |
Are there any differences between commands that you type into the terminal and commands you include in a script?
|
Your terminal runs a shell (most probably bash), which is the one asking for your commands and runs them.
Besides of this interactive mode you can also use your shell to run commands from a file. To execute the commands in your file you can either call the shell directly like bash script or you can start your file with a "shebang" #!/bin/bash and make it executable (chmod +x script). Then you can treat the script like a binary and execute it for example as ./script or put it at a place where you shell is looking for it. (echo $PATH)
Most probably both your interactive shell and the shell used to run is bash.
From the perspective of a "first day learning linux" bash works exactly the same in both modes. - Much later you might stumble about slight differences. If you really want to know about in detail I would suggest reading man bash and search for places mentioning "interactive". (You can search a man page, by pressing /.)
One important thing to note is that the script is run as a new process. This especially means that variables set in the script are not visible in the calling shell.
$ export a=1
$ echo $a
1
$ bash -c 'echo $a;a=2;echo $a' # change the value in a script
1
2
$ echo $a # value not changed here
1
$
Without the export a is not even visible to the inner script.
| Difference between commands in bash script and commands in terminal |
1,410,708,734,000 |
Is there any linux distro that has a git based package manager/installer. I want something similar to FreeBSD Ports (which is CVS based, I think) or Mac OS X Homebrew (git based).
|
There's Exherbo, which uses multiple Git repositories to store its exheres (its term for build recipes similar to Gentoo's ebuilds or BSD's ports). It's still a pretty young distribution, though.
Update: Gentoo recently moved to Git for its package repository. However, I don't think it's set up yet to have normal users get updates via Git (although I believe it's planned to allow that).
| Git based package manager/installer for Linux |
1,410,708,734,000 |
There has been a similar question - but IMHO there has to be a simpler solution. If num-lock is on in the BIOS - why is it turned off during linux boot and/or KDE/Gnome/whatever startup?
|
Linux initializes most peripherals so that they'll be in a known state. This includes the keyboard: Linux's internal data about the keyboard had better match the LEDs, so what Linux does is to turn off the LEDs (as far as I recall, the CPU can't read the state of the LEDs on a PC keyboard) and declare all *Lock to be off.
I like to have NumLock on by default. For Linux text consoles, what I used to do¹ is to run
for t in /dev/tty[0-9]*; do setleds -D +num <$t; done
from a boot script (/etc/rc.local or /etc/init.d/50_local_setleds or wherever the distribution likes to put those).
Nowadays, at least on some distributions such as Debian, you can add LEDS=+num to /etc/console-tools/config (or /etc/kbd/config depending on which one you have).
The X window system has its own keyboard handling, so you need to deal with it separately. What I do is to switch caps lock permanently off (I don't have a Caps Lock key in my layout) and switch num lock permanently on (I don't have a Num Lock key in my layout, and the keypad keys send KP_1 and so on). If you want to retain the modifiers but make Num Lock default on, you can write a small program to call XKbLockModifiers to set the modifier inside X and XChangeKeyboardControl to set the physical LED.
¹ Used to, because I haven't bothered with text consoles in a while.
| Enable num-lock as default in Linux |
1,410,708,734,000 |
Due to a lot of file exchange works between Windows (GBK encoding) and Linux (UTF-8 encoding), it will encounter character encoding issues easily, such as:
zip/tar files whose name contains chinese characters on Windows system, unzip/untar it in Linux system.
run migrated legacy java web application (designed on Windows system, using GBK encoding in JSP) which write GBK-encoding-named files to disk.
ftp get/put GBK-encoding-named files between Windows FTP server and Linux client.
switch LANG environment in Linux.
The common issue of the previous mentioned are file locating/naming. After googled, I got an article Using Unicode in Linux
https://www.linux.com/news/using-unicode-linux/, it said:
the operating system and many utilities do not realize what characters the bytes in file names represent.
So, it's possible to have two files with same name (SAME when their names are decoded by correct character set, but DIFFERENT in bytes), such as 中文.txt, but in different encoding:
[root@fedora test]# ls
???? 中文
[root@fedora test]# ls | iconv -f GBK
中文
涓iconv: illegal input sequence at position 7
[root@fedora test]# ls 中文 && ls $'\xd6\xd0\xce\xc4' | iconv -f gbk
中文
中文
Questions:
Is it possible to config linux filesystem use fixed character encoding (like NTFS use UTF-16 internally) to store file names regardless of LANG/LC_ALL environment?
Or, what I actually want ask is: Is it possible to let file name 中文.txt ($'\xe4\xb8\xad\xe6\x96\x87.txt') in zh_CN.UTF-8 environment and file name 中文.txt ($'\xd6\xd0\xce\xc4.txt') in zh_CN.GBK environment refer to same file?
If it's not configurable, then is it possible to patch kernel to translate character encoding between file-system and current environment (just a question, not request implementation)? and how much performance con effect if it's possible?
|
I have reformulated your questions a bit, for reasons that should
appear evident when you read them in sequence.
1. Is it possible to config linux filesystem use fixed character encoding to store file names regardless of LANG/LC_ALL environment?
No, this is not possible: as you mention in your question, a UNIX file
name is just a sequence of bytes; the kernel knows nothing about
the encoding, which entirely a user-space (i.e., application-level)
concept.
In other words, the kernel knows nothing about LANG/LC_*, so it cannot
translate.
2. Is it possible to let different file names refer to same file?
You can have multiple directory entries referring to the same file;
you can make that through hard links or symbolic links.
Be aware, however, that the file names that are not valid in the
current encoding (e.g., your GBK character string when you're working
in a UTF-8 locale) will display badly, if at all.
3. Is it possible to patch the kernel to translate character encoding between file-system and current environment?
You cannot patch the kernel to do this (see 1.), but you could -in
theory- patch the C library (e.g., glibc) to perform this translation,
and always convert file names to UTF-8 when it calls the kernel, and
convert them back to the current encoding when it reads a file name
from the kernel.
A simpler approach could be to write an overlay filesystem with FUSE,
that just redirects any filesystem request to another location after
converting the file name to/from UTF-8. Ideally you could mount this
filesystem in ~/trans, and when an access is made to
~/trans/a/GBK/encoded/path then the FUSE filesystem really accesses
/a/UTF-8/encoded/path.
However, the problem with these approaches is: what do you do with
files that already exist on your filesystem and are not UTF-8 encoded?
You cannot just simply pass them untranslated, because then you don't
know how to convert them; you cannot mangle them by translating
invalid character sequences to ? because that could create
conflicts...
| Several questions about file-system character encoding on linux |
1,410,708,734,000 |
I am wondering how a driver functions under Linux. Are drivers a single file that can be edited? Is there a list of current drivers in use or is there a different place to find them for each device?
I am especially interested in learning about my network adapter's driver.
If you know where some good documentation is, I would love to read that too.
|
Drivers are very similar to any other program, they can be comprised of multiple source files. Linux devices drivers can be directly compiled into the kernel or a kernel module. Kernel modules have the benefit of being able to be loaded dynamically (i.e. you don't need to compile a new kernel to use them).
You can obviously always look at the Linux source code, but that can be a daunting task at first. However, as with anything in Linux drivers are files. That means other programs access them via the VFS interface. For example, you can control the CDROM via ioctl() calls using its device file.
I would highly recommend checking out Linux Device Drivers. It's freely available and will answer your questions. In particular, you can read through chapter 2 which shows you how to create a simple "Hello, Kernel" module. It may be far more than you are asking for, but you can read the bits and pieces you are interested in. And its free. ;P
| How do Linux drivers work and where do I find them? (esp. NIC driver) |
1,410,708,734,000 |
I have a device that I need to connect to over SSH. The device is connected to my workstation via a direct ethernet connection. I'm attempting to assign the connected device an IP address somehow that I can SSH to, however all of the guides I'm finding have the user configure the IP from whatever device they're working with (namely Raspberry Pi's and so on). This is not something I can do with this device as I've no physical interface to work with.
I've been recommended to setup a DHCP server on my workstation so it would take care of this for me, however I've no idea how to configure it and none of the guides I have followed have been helpful. With that approach, I seem to have been able to bind an IP to the interface the device is connected on, however SSHing to that IP just brings me back to my own machine.
So my main question is: How do I assign an IP address to a device directly connected to my computer via ethernet cable without having any kind of access to the device (no interface, keyboard, monitor, etc). If the answer is to set up a DHCP server on my machine, how do I properly configure this and get an IP I can SSH to?
For reference, I am using Ubuntu 16.04 with OpenSSH installed. The device is also running some flavor of Linux and has SSH software installed, but again there's no way to interact with it except through SSH. I also do not have access to my router, so plugging the device in there and letting the router do the work is not an option.
|
The link given by @steve as a comment is appropriate, but if you want to try something simple first just to see what the device does you can use dnsmasq, which is a simple dns and dhcp server. Install with sudo apt-get install dnsmasq. If this also enables and starts the server you need to stop and disable it.
If, say, your device is on your ethernet interface eth2, and you have done sudo ifconfig eth2 192.168.9.1 to set the interface ip address, then you can try:
sudo dnsmasq -d -C /dev/null --port=0 --domain=localdomain --interface=eth2 --dhcp-range=192.168.9.2,192.168.9.10,99h
which sets up a dhcp server in debug mode (-d), not as a daemon, with dns (port=0) able to offer addresses in the range .2 to .10, and to hold the same ones for 99hours.
If your device broadcasts a request to discover an address you should see it, and the reply (offer):
dnsmasq-dhcp: DHCPDISCOVER(eth2) 94:71:ac:ff:85:9d
dnsmasq-dhcp: DHCPOFFER(eth2) 192.168.9.2 94:71:ac:ff:85:9d
The numbers are the ip address assigned and the device's mac address. You may need to reset or power on the device if it has given up broadcasting. The device might reply to ping 192.168.9.2 and then you can try to ssh too.
You can interrupt the dnsmasq once the address has been offered in this test and put the options in the standard dnsmasq config file and so on.
You may also usefully run sudo tcpdump -i eth2 to see what packets pass.
| How to connect to device via SSH over direct ethernet connection |
1,410,708,734,000 |
I have several USB modems that each have several endpoints: lot of TTYs, a network interface, a cdc-wdm port, and some other things. I'm trying to group them together so that I know, for instance, ttyUSB3, ttyUSB4, wwan1, and cdc-wdm1 all belong to the same physical USB device.
I thought $id was supposed to identify the physical device, so I tried adding $id to the environment with ENV{id}=$id. This seems to work for the network interfaces and serial ports, but not the cdc-wdm ports (id is unset for these ports).
Here is some example data after adding the ENV{id}=$id rules:
rule: SUBSYSTEM=="net", ATTRS{idVendor}=="106c", ATTRS{idProduct}=="3718", ENV{id}="$id"
# udevadm info --query=all --path=/devices/platform/atmel-ehci/usb1/1-1/1-1.3/1-
1.3:1.5/net/wwan0
P: /devices/platform/atmel-ehci/usb1/1-1/1-1.3/1-1.3:1.5/net/wwan0
E: DEVPATH=/devices/platform/atmel-ehci/usb1/1-1/1-1.3/1-1.3:1.5/net/wwan0
E: DEVTYPE=wwan
E: ID_BUS=usb
E: ID_MODEL=PANTECH_UML290
E: ID_MODEL_ENC=PANTECH\x20UML290
E: ID_MODEL_ID=3718
E: ID_REVISION=0000
E: ID_SERIAL=Pantech__Incorporated_PANTECH_UML290
E: ID_TYPE=generic
E: ID_USB_DRIVER=qmi_wwan
E: ID_USB_INTERFACES=:020201:0a0000:ffffff:fffdff:fffeff:fff1ff:
E: ID_USB_INTERFACE_NUM=05
E: ID_VENDOR=Pantech__Incorporated
E: ID_VENDOR_ENC=Pantech\x2c\x20Incorporated
E: ID_VENDOR_ID=106c
E: IFINDEX=5
E: INTERFACE=wwan0
E: SUBSYSTEM=net
E: USEC_INITIALIZED=174833330
E: id=1-1.3
rule: SUBSYSTEM=="usb", KERNEL=="*cdc-wdm*", ENV{id}="$id"
# udevadm info --query=all --path=/devices/platform/atmel-ehci/usb1/1-1/1-1.3/1-
1.3:1.5/usb/cdc-wdm0
P: /devices/platform/atmel-ehci/usb1/1-1/1-1.3/1-1.3:1.5/usb/cdc-wdm0
N: cdc-wdm0
E: DEVNAME=/dev/cdc-wdm0
E: DEVPATH=/devices/platform/atmel-ehci/usb1/1-1/1-1.3/1-1.3:1.5/usb/cdc-wdm0
E: MAJOR=180
E: MINOR=176
E: SUBSYSTEM=usb
E: USEC_INITIALIZED=174788259
|
Okay, first I now understand what the documentation for $id means by
The name of the device matched while searching the devpath upwards for SUBSYSTEMS, KERNELS, DRIVERS and ATTRS.
...and it's not what I thought (which was formed by failing to understand the documentation combined with some experimentation).
By "The name of the device", it's talking about the same thing the KERNEL key matches. The documentation says about the KERNEL key is:
Match the name of the event device.
That is how you know "name" and "KERNEL" are related.
The "matched while searching the devpath upwards for SUBSYSTEMS, KERNELS, DRIVERS and ATTRS" part means that if you specified a "SUBSYSTEMS, KERNELS, DRIVERS, or ATTRS" match in the rule, it will walk up the device tree until it finds a match; the name of the matched device will be used.
So, in my first rule, it was matching with the ATTRS key, and that device happened to be the physical USB device.
Now for my other rule, I had to look at the tree and find something that would match the physical device but not anything below it. Here is my device tree:
# udevadm info --attribute-walk --name=/dev/cdc-wdm0
Udevadm info starts with the device specified by the devpath and then
walks up the chain of parent devices. It prints for every device
found, all possible attributes in the udev rules key format.
A rule to match, can be composed by the attributes of the device
and the attributes from one single parent device.
looking at device '/devices/platform/atmel-ehci/usb1/1-1/1-1.7/1-1.7.2/1-1.7.2:1.5/usb/cdc-wdm0':
KERNEL=="cdc-wdm0"
SUBSYSTEM=="usb"
DRIVER==""
looking at parent device '/devices/platform/atmel-ehci/usb1/1-1/1-1.7/1-1.7.2/1-1.7.2:1.5':
KERNELS=="1-1.7.2:1.5"
SUBSYSTEMS=="usb"
DRIVERS=="qmi_wwan"
ATTRS{bInterfaceNumber}=="05"
ATTRS{bAlternateSetting}==" 0"
ATTRS{bNumEndpoints}=="03"
ATTRS{bInterfaceClass}=="ff"
ATTRS{bInterfaceSubClass}=="f1"
ATTRS{bInterfaceProtocol}=="ff"
ATTRS{supports_autosuspend}=="1"
looking at parent device '/devices/platform/atmel-ehci/usb1/1-1/1-1.7/1-1.7.2':
KERNELS=="1-1.7.2"
SUBSYSTEMS=="usb"
DRIVERS=="usb"
ATTRS{configuration}=="Pantech, Incorporated"
ATTRS{bNumInterfaces}==" 6"
ATTRS{bConfigurationValue}=="1"
ATTRS{bmAttributes}=="c0"
ATTRS{bMaxPower}=="500mA"
ATTRS{urbnum}=="496"
ATTRS{idVendor}=="106c"
ATTRS{idProduct}=="3718"
ATTRS{bcdDevice}=="0000"
ATTRS{bDeviceClass}=="02"
ATTRS{bDeviceSubClass}=="00"
ATTRS{bDeviceProtocol}=="00"
ATTRS{bNumConfigurations}=="1"
ATTRS{bMaxPacketSize0}=="64"
ATTRS{speed}=="480"
ATTRS{busnum}=="1"
ATTRS{devnum}=="12"
ATTRS{devpath}=="1.7.2"
ATTRS{version}==" 2.00"
ATTRS{maxchild}=="0"
ATTRS{quirks}=="0x0"
ATTRS{avoid_reset_quirk}=="0"
ATTRS{authorized}=="1"
ATTRS{manufacturer}=="Pantech, Incorporated"
ATTRS{product}=="PANTECH UML290"
looking at parent device '/devices/platform/atmel-ehci/usb1/1-1/1-1.7':
KERNELS=="1-1.7"
SUBSYSTEMS=="usb"
DRIVERS=="usb"
ATTRS{configuration}==""
ATTRS{bNumInterfaces}==" 1"
ATTRS{bConfigurationValue}=="1"
ATTRS{bmAttributes}=="e0"
ATTRS{bMaxPower}=="100mA"
ATTRS{urbnum}=="188"
ATTRS{idVendor}=="1a40"
ATTRS{idProduct}=="0101"
ATTRS{bcdDevice}=="0111"
ATTRS{bDeviceClass}=="09"
ATTRS{bDeviceSubClass}=="00"
ATTRS{bDeviceProtocol}=="01"
ATTRS{bNumConfigurations}=="1"
ATTRS{bMaxPacketSize0}=="64"
ATTRS{speed}=="480"
ATTRS{busnum}=="1"
ATTRS{devnum}=="3"
ATTRS{devpath}=="1.7"
ATTRS{version}==" 2.00"
ATTRS{maxchild}=="4"
ATTRS{quirks}=="0x0"
ATTRS{avoid_reset_quirk}=="0"
ATTRS{authorized}=="1"
ATTRS{product}=="USB 2.0 Hub"
looking at parent device '/devices/platform/atmel-ehci/usb1/1-1':
KERNELS=="1-1"
SUBSYSTEMS=="usb"
DRIVERS=="usb"
ATTRS{configuration}==""
ATTRS{bNumInterfaces}==" 1"
ATTRS{bConfigurationValue}=="1"
ATTRS{bmAttributes}=="e0"
ATTRS{bMaxPower}=="100mA"
ATTRS{urbnum}=="53"
ATTRS{idVendor}=="1a40"
ATTRS{idProduct}=="0201"
ATTRS{bcdDevice}=="0100"
ATTRS{bDeviceClass}=="09"
ATTRS{bDeviceSubClass}=="00"
ATTRS{bDeviceProtocol}=="02"
ATTRS{bNumConfigurations}=="1"
ATTRS{bMaxPacketSize0}=="64"
ATTRS{speed}=="480"
ATTRS{busnum}=="1"
ATTRS{devnum}=="2"
ATTRS{devpath}=="1"
ATTRS{version}==" 2.00"
ATTRS{maxchild}=="7"
ATTRS{quirks}=="0x0"
ATTRS{avoid_reset_quirk}=="0"
ATTRS{authorized}=="1"
ATTRS{product}=="USB 2.0 Hub [MTT]"
looking at parent device '/devices/platform/atmel-ehci/usb1':
KERNELS=="usb1"
SUBSYSTEMS=="usb"
DRIVERS=="usb"
ATTRS{configuration}==""
ATTRS{bNumInterfaces}==" 1"
ATTRS{bConfigurationValue}=="1"
ATTRS{bmAttributes}=="e0"
ATTRS{bMaxPower}==" 0mA"
ATTRS{urbnum}=="26"
ATTRS{idVendor}=="1d6b"
ATTRS{idProduct}=="0002"
ATTRS{bcdDevice}=="0206"
ATTRS{bDeviceClass}=="09"
ATTRS{bDeviceSubClass}=="00"
ATTRS{bDeviceProtocol}=="00"
ATTRS{bNumConfigurations}=="1"
ATTRS{bMaxPacketSize0}=="64"
ATTRS{speed}=="480"
ATTRS{busnum}=="1"
ATTRS{devnum}=="1"
ATTRS{devpath}=="0"
ATTRS{version}==" 2.00"
ATTRS{maxchild}=="3"
ATTRS{quirks}=="0x0"
ATTRS{avoid_reset_quirk}=="0"
ATTRS{authorized}=="1"
ATTRS{manufacturer}=="Linux 2.6.39.4-acnbfx100 ehci_hcd"
ATTRS{product}=="Atmel EHCI UHP HS"
ATTRS{serial}=="atmel-ehci"
ATTRS{authorized_default}=="1"
looking at parent device '/devices/platform/atmel-ehci':
KERNELS=="atmel-ehci"
SUBSYSTEMS=="platform"
DRIVERS=="atmel-ehci"
ATTRS{companion}==""
looking at parent device '/devices/platform':
KERNELS=="platform"
SUBSYSTEMS==""
DRIVERS==""
The device I want to match is /devices/platform/atmel-ehci/usb1/1-1/1-1.7/1-1.7.2'. You can see that the DRIVERS for that device is 'usb' and nothing below it will match that. The following rule solves my problem, should even be a generic solution since I'm pretty sure no endpoint of a device would be handled by the usb driver.
DRIVERS=="usb", KERNEL=="*cdc-wdm*", ENV{id}="$id", RUN="/usr/local/bin/modem_setup.sh"
And the is the result I was looking for all along:
# udevadm info --query=all --name=/dev/cdc-wdm0
P: /devices/platform/atmel-ehci/usb1/1-1/1-1.7/1-1.7.2/1-1.7.2:1.5/usb/cdc-wdm0
N: cdc-wdm0
E: DEVNAME=/dev/cdc-wdm0
E: DEVPATH=/devices/platform/atmel-ehci/usb1/1-1/1-1.7/1-1.7.2/1-1.7.2:1.5/usb/cdc-wdm0
E: MAJOR=180
E: MINOR=176
E: SUBSYSTEM=usb
E: USEC_INITIALIZED=12243969
E: id=1-1.7.2
| udev: How do you identify the physical device that a sys device belongs to? |
1,410,708,734,000 |
I am using Arch Linux with GNOME, I want to install FreeBSD alongside Arch Linux with the following requirements :
I want to keep the Linux GRUB and add an entry of FreeBSD to it.
I want to use different SWAP partitions for Linux and BSD.
I Do not want to Destroy my Linux /boot
My System Information :
I am using Arch Linux : UEFI mode.
Disk is GPT
My partition Layout Looks like this :
.
[severus@Tux ~]$ sudo parted -l
Model: ATA TOSHIBA MQ01ABD1 (scsi)
Disk /dev/sda: 1000GB
Sector size (logical/physical): 512B/4096B
Partition Table: gpt
Disk Flags:
Number Start End Size File system Name Flags
1 1049kB 1076MB 1075MB fat32 ESP boot, esp
2 1076MB 76.2GB 75.2GB ext4 root
3 76.2GB 125GB 48.3GB ext4 home
4 125GB 134GB 9837MB linux-swap(v1) swap
5 134GB 564GB 429GB ext4
6 564GB 832GB 268GB ext4
7 832GB 914GB 82.0GB ext4
8 973GB 1000GB 26.8GB ext4 CZ-Backup
I wish to install FreeBSD on the Un-allocated space preceding /dev/sda8
To be more precise, I am stuck at partitioning during the FreeBSD Installation process. i.e, In the Documentation, It is said that FreeBSD uses specific types of partitions ( freebsd-boot, freebsd-ufs, freebsd-swap) .
Is freebsd-boot same as EFI-System-Partition ? , Should I create a new freebsd-boot or is there any way to use the existing Linux-ESP?
I got some relevant threads, but they seems to be out-dated :
https://bbs.archlinux.org/viewtopic.php?id=111660
|
You can install FreeBSD alongside any linux distro with the following requirements :
I want to keep the Linux GRUB and add an entry of FreeBSD to it.
I want to use different SWAP partitions for Linux and BSD.
I Do not want to Destroy my Linux /boot
You need to create 3 partitions : swap: (4G) , /boot (512K) and the / partition.
To create the boot partition:
Choose Create :
Type : freebsd-boot
Size : 512k
Label boot
To create the swap partition :
Type : freebsd-swap
Size : 4G
Label : swap
To create the root partition:
Type : freebsd-ufs
Size: keep it unchanged
Mount point : /
Label : root
Choose finish then select Commit to start the installation and hit Enter.
Once the installation is done reboot into arch-linux , open the /etc/grub.d/40_custom file then add the new entry:
menuentry "FreeBSD" {
insmod ufs2
set root=(hd0,gpt8)
kfreebsd /boot/loader
}
Run:
grub-mkconfig -o /boot/grub/grub.cfg
Reboot into Freebsd to install Xorg , Desktop ...
Is freebsd-boot same as EFI-System-Partition ? , Should I create a new freebsd-boot or is there any way to use the existing Linux-ESP?
You should create a new freebsd-boot partition , if you forget to add it , the installer will ask you for adding the boot partition automatically.
| Installing FreeBSD alongside Linux |
1,410,708,734,000 |
My basic assumption is that when a process' only limiting factors are disk and CPU, then total system "iowait" + CPU usage should equal at least 100% of one logical CPU. (In other cases this will not hold. E.g. when downloading a file using wget, the network is often the limiting factor).
This assumption is violated by a simple test. Is this expected? If it is expected, is there a set of conditions where I should expect my assumption to hold true?
There is some background about "iowait" here: How does a CPU know there is IO pending? The answer here quotes the counter-intuitive idea, that cumulative iowait "may decrease in certain conditions". I wonder if my simple test can be triggering such an undocumented condition?
UPDATE: Please skip to the answer.
The answer has a simpler test than the one I used originally. I preserved the original question below. The original question might show some additional details.
Original question
In a short test, I use dd to request the kernel to generate random bytes, and write them to a file. I run the dd command inside perf stat, just to get a count of the CPU time spent inside the kernel. I also run it inside perf trace -s, to report the time spent inside write(). At the same time, I run vmstat 5 in another terminal, to see the system "iowait".
I expected I would see at least one whole CPU as "non-idle", i.e. 100% of the time it is either running, or halted but waiting for IO ("iowait" state). It was not.
(Also, I was expecting to see "iowait" time roughly match the time spent in write(). But it did not appear to do so.)
The detailed results and test environment are shown below. Also shown is an alternative test, where my assumption did hold. Note: it was necessary to run perf stat inside perf trace, not the other way around. This is detailed here: Does "perf stat" (and "time" !) show incorrect results when running "perf trace -s" ?
Background information on "iowait"
Following is the definition taken from the sar manpage:
%iowait:
Percentage of time that the CPU or CPUs were idle during which the
system had an outstanding disk I/O request.
Therefore, %iowait means that from the CPU point of view, no tasks
were runnable, but at least one I/O was in progress. iowait is simply
a form of idle time when nothing could be scheduled. The value may or
may not be useful in indicating a performance problem, but it does
tell the user that the system is idle and could have taken more work.
https://support.hpe.com/hpsc/doc/public/display?docId=c02783994
There is also a longer article: Understanding I/O Wait (or why 0% Idle can be OK). This explains how you can see the definition clearly from the kernel code. The code has changed somewhat, but the idea is still clear:
/*
* Account for idle time.
* @cputime: the CPU time spent in idle wait
*/
void account_idle_time(u64 cputime)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
struct rq *rq = this_rq();
if (atomic_read(&rq->nr_iowait) > 0)
cpustat[CPUTIME_IOWAIT] += cputime;
else
cpustat[CPUTIME_IDLE] += cputime;
}
The article also shows a number of related experiments on a single-CPU system. Some of the experiments even use dd with if=/dev/urandom ! However the experiments do not include my test dd if=/dev/urandom of=test.out . It only uses dd if=/dev/urandom of=/dev/null .
"IO wait" is a bit more tricky to think about now because we use multi-CPU systems, but I think I still understand it, based on the quoted code.
Environment
I have four logical CPUs.
I use LVM, and the ext4 filesystem. I am not using any encryption on my disk or filesystem. I do not have any network filesystem mounted at all, so I am not reading or writing a network filesystem.
The results below are from kernel 4.20.15-200.fc29.x86_64 , using the noop IO scheduler. The cfq IO scheduler also gives similar results.
(I have also seen similar results on a kernel build which was based on a similar configuration, but was closer to kernel version 5.1, and using mq-deadline. So that was using the new blk-mq code).
Test and results
$ sudo perf trace -s \
perf stat \
dd if=/dev/urandom of=test.out bs=1M oflag=direct count=3000
3000+0 records in
3000+0 records out
3145728000 bytes (3.1 GB, 2.9 GiB) copied, 31.397 s, 100 MB/s
Performance counter stats for 'dd if=/dev/urandom of=test.out bs=1M oflag=direct count=3000':
18,014.26 msec task-clock # 0.574 CPUs utilized
3,199 context-switches # 0.178 K/sec
4 cpu-migrations # 0.000 K/sec
328 page-faults # 0.018 K/sec
45,232,163,658 cycles # 2.511 GHz
74,538,278,379 instructions # 1.65 insn per cycle
4,372,725,344 branches # 242.737 M/sec
4,650,429 branch-misses # 0.11% of all branches
31.398466725 seconds time elapsed
0.006966000 seconds user
17.910332000 seconds sys
Summary of events:
...
dd (4620), 12156 events, 12.0%
syscall calls total min avg max stddev
(msec) (msec) (msec) (msec) (%)
--------------- -------- --------- --------- --------- --------- ------
read 3007 17624.985 0.002 5.861 12.345 0.21%
write 3003 13722.837 0.004 4.570 179.928 2.63%
openat 12 0.371 0.002 0.031 0.267 70.36%
...
I read the iowait figure from the wa column of vmstat. You can tell when the test is running by looking at the io column (bo = 1K blocks output).
$ vmstat 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
0 0 0 5126892 176512 1486060 0 0 1788 4072 321 414 4 4 83 9 0
1 0 0 5126632 176520 1485988 0 0 0 7 212 405 0 1 99 0 0
0 0 0 5126884 176520 1485988 0 0 0 0 130 283 0 0 99 0 0
0 0 0 5126948 176520 1485908 0 0 0 1 157 325 0 0 99 0 0
0 0 0 5126412 176520 1486412 0 0 115 0 141 284 0 0 99 0 0
0 2 0 5115724 176548 1487056 0 0 0 6019 18737 10733 3 6 89 2 0
1 0 0 5115708 176580 1487104 0 0 3 91840 1276 990 0 13 77 9 0
1 0 0 5115204 176600 1487128 0 0 2 91382 1382 1014 0 14 81 4 0
1 0 0 5115268 176636 1487084 0 0 4 88281 1257 901 0 14 83 3 0
0 1 0 5113504 177028 1487764 0 0 77 92596 1374 1111 0 15 83 2 0
1 0 0 5114008 177036 1487768 0 0 0 113282 1460 1060 0 16 81 2 0
1 0 0 5113472 177044 1487792 0 0 0 110821 1489 1118 0 16 74 10 0
0 0 0 5123852 177068 1487896 0 0 0 20537 631 714 1 3 94 2 0
0 0 0 5123852 177076 1487856 0 0 0 10 324 529 2 1 98 0 0
2 0 0 5123852 177084 1487872 0 0 0 70 150 299 0 0 99 0 0
Test results where it does hold (inside a VM)
I tried the same test inside a VM with 1 CPU, which was running the kernel 5.0.9-301.fc30.x86_64 and using mq-deadline (and hence blk-mq). In this test, it worked how I expected it to.
$ sudo perf trace -s \
perf stat \
dd if=/dev/urandom of=test.out bs=1M oflag=direct count=3000
[sudo] password for alan-sysop:
3000+0 records in
3000+0 records out
3145728000 bytes (3.1 GB, 2.9 GiB) copied, 46.8071 s, 67.2 MB/s
Performance counter stats for 'dd if=/dev/urandom of=test.out bs=1M oflag=direct count=3000':
18,734.89 msec task-clock # 0.400 CPUs utilized
16,690 context-switches # 0.891 K/sec
0 cpu-migrations # 0.000 K/sec
328 page-faults # 0.018 K/sec
<not supported> cycles
<not supported> instructions
<not supported> branches
<not supported> branch-misses
46.820355993 seconds time elapsed
0.011840000 seconds user
18.531449000 seconds sys
Summary of events:
...
dd (1492), 12156 events, 38.4%
syscall calls total min avg max stddev
(msec) (msec) (msec) (msec) (%)
--------------- -------- --------- --------- --------- --------- ------
write 3003 28269.070 0.019 9.414 5764.657 22.39%
read 3007 18371.469 0.013 6.110 14.848 0.53%
execve 6 10.399 0.012 1.733 10.328 99.18%
...
Output of vmstat 5:
$ vmstat 5
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
0 0 0 726176 52128 498508 0 0 2040 231 236 731 7 5 77 11 0
0 0 0 726176 52136 498508 0 0 0 10 25 46 0 0 99 1 0
0 0 0 726208 52136 498508 0 0 0 0 29 56 0 0 100 0 0
0 1 0 702280 55944 511780 0 0 2260 13109 4399 9049 3 17 55 25 0
0 1 0 701776 56040 511960 0 0 18 129582 1406 1458 0 73 0 27 0
0 2 0 701524 56156 512168 0 0 22 87060 960 991 0 50 0 50 0
3 1 0 701524 56228 512328 0 0 14 118170 1301 1322 0 68 0 32 0
1 1 0 701272 56260 512392 0 0 6 86426 994 982 0 53 0 46 0
0 2 0 701020 56292 512456 0 0 6 56115 683 660 0 37 0 63 0
3 2 0 700540 56316 512504 0 0 5 33450 446 457 0 26 0 74 0
0 2 0 700860 56332 512536 0 0 3 16998 311 240 0 19 0 81 0
1 2 0 700668 56368 512616 0 0 7 32563 443 428 0 24 0 76 0
1 0 0 700668 56392 512648 0 0 3 20338 245 272 0 12 0 88 0
0 1 0 707096 56408 512920 0 0 54 20913 312 530 0 12 79 8 0
0 0 0 707064 56432 512920 0 0 0 49 39 64 0 0 45 55 0
0 0 0 707064 56432 512920 0 0 0 0 24 46 0 0 100 0 0
0 0 0 707064 56432 512920 0 0 0 80 28 47 0 0 100 0 0
I tried hot-adding a CPU to the VM and testing again. The results were variable: sometimes it showed about 0% in the idle column, and sometimes it showed about 50% idle (i.e. one out of two CPUs). In the case of 0% "idle", "iowait" was very high i.e. more than one CPUs' worth. I.e. my expectation point 2 was not correct. I can begrudgingly accept this apparent limitation of "iowait" on multi-CPU systems. (Though I don't quite understand it. If someone wants to explain it exactly, that would be great). However, "idle" was not above 50% in either case, so these tests were still consistent with my first assumption about "iowait".
I tried shutting the VM down and starting it with 4 CPUs. Similarly, often I had exactly 75% idle, and sometimes I had as low as 50% idle, but I did not see more than 75% idle (i.e. more than three out of four CPUs).
Whereas on the physical system with 4 CPUs, I can still reproduce the result of more than 80% idle as shown above.
|
Content notice: this post includes links to various Linux discussion and code. Some linked content does not meet the current Code of Conduct for StackExchange or for Linux. Mostly they "insult the code [but not the person]". However some language is used, that should simply not be repeated. I ask you to avoid imitating, parrotting, or debating such language.
Re: iowait v.s. idle accounting is "inconsistent" - iowait is too low
On 05/07/2019 12:38, Peter Zijlstra wrote:
On Fri, Jul 05, 2019 at 12:25:46PM +0100, Alan Jenkins wrote:
My cpu "iowait" time appears to be reported incorrectly. Do you know why
this could happen?
Because iowait is a magic random number that has no sane meaning.
Personally I'd prefer to just delete the whole thing, except ABI :/
Also see the comment near nr_iowait()
Thanks. I take [the problems mentioned in current documentation] as being different problems, but you mean there is not much demand (or point) to "fix" my issue.
I found my problem. It was already noticed five years ago, and it would not be trivial to fix.
"iowait" time is updated by the function account_idle_time():
/*
* Account for idle time.
* @cputime: the CPU time spent in idle wait
*/
void account_idle_time(u64 cputime)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
struct rq *rq = this_rq();
if (atomic_read(&rq->nr_iowait) > 0)
cpustat[CPUTIME_IOWAIT] += cputime;
else
cpustat[CPUTIME_IDLE] += cputime;
}
This works as I expected, if you are approximating cpu time by "sampling" with the traditional timer interrupt ("tick"). However, it may not work if the tick is turned off during idle time to save power - NO_HZ_IDLE. It may also fail if you allow the tick to be turned off for performance reasons - NO_HZ_FULL - because that requires starting VIRT_CPU_ACCOUNTING. Most Linux kernels use the power-saving feature. Some embedded systems do not use either feature. Here is my explanation:
When the IO is complete, the device sends an interrupt. The kernel interrupt handler wakes the process using try_to_wake_up(). It subtracts one from the nr_iowait counter:
if (p->in_iowait) {
delayacct_blkio_end(p);
atomic_dec(&task_rq(p)->nr_iowait);
}
If the process is woken on an idle CPU, that CPU calls account_idle_time(). Depending on which configuration applies, this is called either from tick_nohz_account_idle_ticks() from __tick_nohz_idle_restart_tick(), or from vtime_task_switch() from finish_task_switch().
By this time, ->nr_iowait has already been decremented. If it is reduced to zero, then no iowait time will be recorded.
This effect can vary: it depends which CPU the process is woken on. If the process is woken on the same CPU that received the IO completion interrupt, the idle time could be accounted earlier, before ->nr_iowait is decremented. In my case, I found CPU 0 handles the ahci interrupt, by looking at watch cat /proc/interrupts.
I tested this with a simple sequential read:
dd if=largefile iflag=direct bs=1M of=/dev/null
If I pin the command to CPU 0 using taskset -c 0 ..., I see "correct" values for iowait. If I pin it to a different CPU, I see much lower values. If I run the command normally, it varies depending on scheduler behaviour, which has changed between kernel versions. In recent kernels (4.17, 5.1, 5.2-rc5-ish), the command seems to spend about 1/4 of the time on CPU 0, because "iowait" time is reduced to that fraction.
(Not explained: why running this test on my virtual machine now seems to reproduce "correct" iowait, for each (or any) CPU. I suspect this might involve IRQ_TIME_ACCOUNTING, although this feature is also being used in my tests outside the VM.
I also have not confirmed exactly why suppressing NO_HZ_IDLE gives "correct" iowait for each CPU on 4.17+, but not on 4.16 or 4.15.
Running this test on my virtual machine seems to reproduce "correct" iowait, for each (or any) CPU. This is due to IRQ_TIME_ACCOUNTING. It is also used in the tests outside the VM, but I get more interrupts when testing inside the VM. Specifically, there are more than 1000 "Function call interrupts" per second on the virtual CPU that "dd" runs on.
So you should not rely too much on the details of my explanation :-)
There is some background about "iowait" here: How does a CPU know there is IO pending? The answer here quotes the counter-intuitive idea, that cumulative iowait "may decrease in certain conditions". I wonder if my simple test can be triggering such an undocumented condition?
Yes.
When I first looked this up, I found talk of "hiccups". Also, the problem was illustrated by showing the cumulative "iowait" time was non-monotonic. That is it sometimes jumped backwards (decreased). It was not as straightforward as the test above.
However, when they investigated they found the same fundamental problem. A solution was proposed and prototyped, by Peter Zijlstra and Hidetoshi Seto respectively. The problem is explained in the cover message:
[RFC PATCH 0/8] rework iowait accounting (2014-07-07)
I found no evidence of progress beyond this. There was an open question on one of the details. Also, the full series touched specific code for the PowerPC, S390, and IA64 CPU architectures. So I say this is not trivial to fix.
| My basic assumption about system "iowait" does not hold |
1,301,018,892,000 |
I just installed Linux Mint 17 (MATE) on an old laptop and everything works amazing, however I can't seem to get it to connect to my WiFi network. All my other computers can get access, plus, before when the laptop has Windows XP, it could also find and connect. Is there a way to check if it's even detecting the correct network? If so, how would I set up a proper connection to the network?
There is nothing wrong with my network nor the laptop, so it must be Mint's fault.
Edit:
Output of iwconfig:
lo no wireless extensions.
eth0 no wireless extensions.
Output of lspci -nn | grep 0280:
02:04.0 Network controller [0280]: Broadcom Corporation BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller [14e4:4318] (rev 02)
|
This answer assumes that you can connect your machine to the network using a cable and so get internet access. If that assumption is wrong, let me know and I'll modify this.
You need to install the driver for your wireless card. The driver support table of the Linux Wireless page lists it as supported so you should be able to get everything working by simply running:
sudo apt-get install firmware-b43-installer
If this does not work leave me a comment, you might need to tweak it a bit.
Further reading:
http://forums.linuxmint.com/viewtopic.php?f=194&t=139947&start=20
https://help.ubuntu.com/community/WifiDocs/Driver/bcm43xx
| Connecting Linux Mint to WiFi network |
1,301,018,892,000 |
After recently discovering tmux and Tmuxinator, I've been trying to set up a development environment to use.
Per protocol, we aren't allowed to store passwords/passphrases in scripts. So what I'm looking for is a wait for tmux to wait for the SSH tunnel to get set up (password supplied, enter pressed, and logged in).
I know that there's a "wait-for" command in tmux 1.8+. I'm running 1.9a via Cygwin. But even though I've read over the documentation, I'm just having a difficult time understanding it.
tmux new-session -s development -n editor -d
tmux split-window -v
tmux split-window -v
"Need to send to all panes.
tmux send-keys -t development 'ssh [email protected]' C-m
So, here's a very simple version of what I have.
Thoughts? I know I can synchronize-sessions, I'm still working out the kinks in this.
Edit:
Looking into commands, and pulling variables from the pane to the command from synchronized-panes. This might be a "better" way to go about, until I can figure out how to get TMUX to prompt me for user-input.
Might issue a feature request.
|
Some notes of wait-for
So the basic usage of wait-for isn't too complicated if you think of it as analogous to threading concurrency primitives
It's not really connected to other tmux functionality, just a convenient implementation of IPC.
wait-for event_name is like waiting for an event
wait-for -S event_name is a means of signalling an event
The -U and -L options are kind of orthogonal and act like semaphores
Addressing your question directly
You can solve these sorts of race condition with wait-for but only if commands are synchronous.
tmux send-keys 'sync-command ; tmux wait-for -S command-finished' C-m
tmux wait-for command-finished
The problem that you have here is that ssh command isn't synchronous: you can't tell when it has finished.
Looking through the manual we can find the LocalCommand directive which seems to do what we want: run a command locally after the connection has finished so we can call
ssh [email protected] -o 'PermitLocalCommand yes' -o 'LocalCommand tmux wait-for -S done'
| Have tmux wait until I SSH in, to complete rest of Tmuxinator script |
1,301,018,892,000 |
There have been a lot of questions about RAM Disks and I am aware of ramfs and tmpfs which allow the use of ram as a block device. However my interest is in using a fixed memory address range as a block device.
This arises from the necessity to use non-volatile RAM available in my system. I have 6GB of RAM available, and 8GB of non-volatile RAM present. The output of /proc/iomem gives me the following
100000000-17fffffff : System RAM
180000000-37fffffff : reserved
Here the region from 6GB to 14GB corresponds to the Non-volatile RAM region which is marked by the E820 BIOS memory map as reserved. My main intention is to use this NVRAM as a block device in linux. This is useful for testing NVRAM systems. Is there any linux command already present which would allow me to use this region as a block device, or do I have to write my own kernel device driver to facilitate the same?
|
I am not an expert on device drivers, however here are some pointers for your R&D:
if memory is marked as "reserved", the OS cannot touch it; you will have to find a way to either have the BIOS mark it as available to the OS, or use direct low-level ioctls to control it
if Linux could see the memory, you still would not have an easy way to prevent Linux from using it as any other block of RAM; an attempt could be tried by marking such RAM as "bad" and then modifying the kernel to still make a special use out of it (please check kernel documentation regarding this, it has changed a lot since last time I hacked into it and it's evolving at a great speed)
considering the above as a preliminary (and non-definitive nor exhaustive) feasibility study, I would say writing your ramdisk blockdevice driver is the most sane option in your case, and perhaps you should contribute it back to Linux kernel and/or team up with people already trying this (perhaps a better place for this question is the Linux Kernel Mailing list, if you haven't yet posted there)
Some other relevant sources:
Current ramdisk driver
A somewhat old (2005) document about block drivers
A simple block driver for Linux Kernel 2.6.31 (careful: a lot has changed in time)
| Reserve fixed RAM memory region as a block device ( with a given start physical address) |
1,301,018,892,000 |
My CPU usage is almost 90%+
After investigating the output of htop I see, There is a process with this following Command which takes too much cpu usage
/usr/lib/xorg/Xorg -nolisten tcp :0 vt1 -keeptty -auth /tmp/serverauth.eEvrhpxBUl
take a look at the whole data
alamin 1635 1634 31 06:12 tty1 00:35:13 /usr/lib/xorg/Xorg -nolisten tcp :0 vt1 -keeptty -auth /tmp/serverauth.eEvrhpxBUl
alamin 9081 26703 0 08:04 pts/0 00:00:00 grep --color=auto --exclude-dir=.bzr --exclude-dir=CVS --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn Xorg
lspci output
00:00.0 Host bridge: Intel Corporation Broadwell-U Host Bridge -OPI (rev 09)
00:02.0 VGA compatible controller: Intel Corporation HD Graphics 5500 (rev 09)
00:03.0 Audio device: Intel Corporation Broadwell-U Audio Controller (rev 09)
00:14.0 USB controller: Intel Corporation Wildcat Point-LP USB xHCI Controller (rev 03)
00:16.0 Communication controller: Intel Corporation Wildcat Point-LP MEI Controller #1 (rev 03)
00:1b.0 Audio device: Intel Corporation Wildcat Point-LP High Definition Audio Controller (rev 03)
00:1c.0 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #1 (rev e3)
00:1c.2 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #3 (rev e3)
00:1c.3 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #4 (rev e3)
00:1c.4 PCI bridge: Intel Corporation Wildcat Point-LP PCI Express Root Port #5 (rev e3)
00:1d.0 USB controller: Intel Corporation Wildcat Point-LP USB EHCI Controller (rev 03)
00:1f.0 ISA bridge: Intel Corporation Wildcat Point-LP LPC Controller (rev 03)
00:1f.2 SATA controller: Intel Corporation Wildcat Point-LP SATA Controller [AHCI Mode] (rev 03)
00:1f.3 SMBus: Intel Corporation Wildcat Point-LP SMBus Controller (rev 03)
06:00.0 Network controller: Intel Corporation Wireless 3160 (rev 83)
07:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8101/2/6E PCI Express Fast/Gigabit Ethernet controller (rev 07)
08:00.0 3D controller: NVIDIA Corporation GK208M [GeForce 920M] (rev a1)
output of mpstat -P ALL
Linux 4.10.0-33-generic (laptop) 08/29/2017 _x86_64_ (4 CPU)
08:55:25 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
08:55:25 AM all 47.07 0.01 18.16 4.53 0.00 0.52 0.00 0.00 0.00 29.70
08:55:25 AM 0 48.75 0.01 17.76 4.44 0.00 0.18 0.00 0.00 0.00 28.87
08:55:25 AM 1 47.76 0.02 17.03 4.06 0.00 1.59 0.00 0.00 0.00 29.55
08:55:25 AM 2 47.95 0.01 18.64 5.16 0.00 0.22 0.00 0.00 0.00 28.02
08:55:25 AM 3 43.81 0.01 19.24 4.47 0.00 0.09 0.00 0.00 0.00 32.38
output of vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
r b swpd free buff cache si so bi bo in cs us sy id wa st
2 0 0 5918180 57512 905904 0 0 202 28 1848 2469 48 19 29 4 0
If you need any more data. Just ask....
Please give me a suggestion to solve it.
|
Thanks to @dirkt. The problem was of another process -- i3bar -- which was trying to display a lot all the time. I investigated a little in the config and figured out the bottleneck.
| Too Much CPU Usage by /usr/lib/xorg/Xorg [closed] |
1,301,018,892,000 |
I use KVM to manage my virtual machines. I am trying to limit the resources provided for VMs. I am able to limit the CPU and memory allocated for VMs using libvirt/cgroups. Now I want to control the disk time allotted for each VM by applying some weights. I looked at blkio control from cgroups. Since VM is just a Linux process, I will be able to use cgroups but I am not sure whether it will work for asynchronous IO too. If not, can someone suggest a good alternative solution?
|
Blkio in cgroup terminology stands for access to I/O on block devices. It does not seem to be about regulating all the different ways software developers have at hand for I/O-related purposes.
It seems to be targeted mainly to I/O on devices, not on the way software has access to devices. It can limit the number of iops, the bandwidth or a weight with other processes, in other things. It seems that buffered write is not supported by blockio at the moment. It's in the official documentation:
Currently, the Block I/O subsystem does not work for buffered write operations. It is primarily targeted at direct I/O, although it works for buffered read operations.
If you take a look at this presentation from Linda Wang and Bob Kozdemba of Red Hat, on page 20+, you'll see that the graph is about the device bandwidth per VM, not about random vs blocking vs asynchronous I/O.
It seems there has been recent work by Red Hat to implement it directly into virsh. It has been released last week in libvirt 0.9.9. In a few months, you'll be able to do something like this in your favorite distribution:
virsh blkiotune domA --device-weights /dev/sda,250
virsh blkiotune domB --device-weights /dev/sda,750
| Weight-based block IO control for VMs |
1,301,018,892,000 |
In short:
mkfifo fifo; (echo a > fifo) &; (echo b > fifo) &; cat fifo
What I expected:
a
b
since the first echo … > fifo should be the first to have opened the file, so I expect that process to be the first to write to it (with its open unblocking first).
What I get:
b
a
To my surprise, this behaviour also happened when opening two separate terminals to do the writing in definitely independent processes.
Am I misunderstanding something about the first-in, first-out semantics of a named pipe?
Stephen suggested adding a delay:
#!/usr/bin/zsh
delay=$1
N=$(( $2 - 1 ))
out=$(for n in {00..$N}; do
mkfifo /tmp/fifo$n
(echo $n > /tmp/fifo$n) &
sleep $delay
(echo $(( $n + 1000 )) > /tmp/fifo$n )&
# intentionally using `cat` here to not step into any smartness
cat /tmp/fifo$n | sort -C || echo +1
rm /tmp/fifo$n
done)
echo "$(( $res )) inverted out of $(( $N + 1 ))"
Now, this works 100% correct (delay = 0.1, N = 100).
Still, running mkfifo fifo; (echo a > fifo) &; sleep 0.1 ; (echo b > fifo) &; cat fifo manually almost always yields the inverted order.
In fact, even copying and pasting the for loop itself fails about half of the time. I'm very confused about what's happening here.
|
This has nothing to do with FIFO semantics of pipes, and doesn’t prove anything about them either way. It has to do with the fact that FIFOs block on opening until they are opened for both writing and reading; so nothing happens until cat opens fifo for reading.
since the first echo should be first.
Starting processes in the background means that you don’t know when they will actually be scheduled, so there’s no guarantee that the first background process will do its work before the second one. The same applies to unblocking blocked processes.
You can improve the odds, while still using background processes, by artificially delaying the second one:
rm fifo; mkfifo fifo; echo a > fifo & (sleep 0.1; echo b > fifo) & cat fifo
The longer the delay, the better the odds: echo a > fifo blocks waiting to finish opening fifo, cat starts and opens fifo which unblocks echo a, and then echo b runs.
However the major factor here is when cat opens the FIFO: until then, the shells block trying to set up the redirections. The output order seen ultimately depends on the order in which the writing processes are unblocked.
You’ll get different results if you run cat first:
rm fifo; mkfifo fifo; cat fifo & echo a > fifo & echo b > fifo
That way, opening fifo for writing will tend not to block (still, without guarantees), so you’ll see a first with a higher frequency than in the first setup. You’ll also see cat finishing before echo b runs, i.e. only a being output.
| Linux named pipes: not as FIFO as thought |
1,301,018,892,000 |
For example, I looking for files and directories in some directory:
ubuntu@example:/etc/letsencrypt$ sudo find . -name example.com*
./archive/example.com
./renewal/example.com.conf
./live/example.com
ubuntu@example:/etc/letsencrypt$
How can I mark that ./archive/example.com and ./live/example.com are directories in the output above?
|
Print the file type along with the name with -printf "%y %p\n":
$ sudo find . -name 'example.com*' -printf "%y %p\n"
d ./archive/example.com
f ./renewal/example.com.conf
d ./live/example.com
The use of -printf assumes GNU find (the most common find implementation on Linux systems).
| How to mark directories in the output of the `find` command? |
1,301,018,892,000 |
I forgot to install the desktop environment while installing Debian 12.
I'm stuck in tty1 when installing, no GUI, only text. I've asked on a Facebook group, and people there say I forgot to install the desktop environment.
What should I do?
|
Assuming you want to continue from where you are now, these instructions will help you get the graphical interface installed. However, since you are using a freshly installed system you might find it easier simply to rerun the installation from scratch, this time remembering to include the desired graphical interface.
Log in using the username and password you set up earlier. You will not see anything when you type in the password. No stars. Nothing. Remember to hit Enter at the end of the username and password rather than Tab. You cannot use either the mouse or cursor keys at this point (if you make a mistake, delete what you've typed with Backspace, do not try to move back with the cursor.)
Username: ari
Password: _
Linux pi 4.9.35-v7+ #1014 SMP Fri Jun 30 14:47:43 BST 2017 armv7l
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
ari:~$ _
You now have a prompt (it will typically end with $) at which you can enter commands. I've shown the cursor as _. In your case it may be a flashing line or block.
Run su -c tasksel (and hit Enter). Enter the root password you set for the root account during installation when prompted (remember you'll see nothing happen while you type the password):
ari:~$ su -c tasksel
Password: _
Alternatively, if you have already installed sudo or definitely did not set a root password, try using sudo tasksel (and hit Enter). Enter your password if/when prompted:
ari:~$ sudo tasksel
Sudo password for ari: _
Either way, you should start the Task Selection tool, which will look something like this:
Package configuration
┌───────────────────────┤ Software selection ├────────────────────────┐
│ You can choose to install one or more of the following predefined │
│ collections of software. │
│ │
│ Choose software to install: │
│ │
│ [*] Debian desktop environment │
│ [ ] ... GNOME │
│ [ ] ... Xfce │
│ [ ] ... GNOME Flashback │
│ [ ] ... KDE Plasma │
│ [ ] ... Cinnamon │
│ [*] ... MATE │
│ [ ] ... LXDE │
│ [ ] ... LXQt │
│ [ ] web server │
│ [ ] SSH server │
│ [ ] laptop │
│ │
│ │
│ <Ok> <Cancel> │
│ │
└─────────────────────────────────────────────────────────────────────┘
Using the cursor keys ↑ ↓ to move up and down and Space to select/deselect, choose the Debian desktop environment. By default this will automatically include GNOME, but you might prefer Cinnamon or MATE. You'll see * alongside the two items you select.
Use Tab to move to the <Ok> item and hit Space once more to accept
| Forgot to install the desktop environment while installing debian 12 |
1,301,018,892,000 |
I am going to learn how to use the command line. Specifically, I will be using the book: "The Linux Command Line: A Complete Introduction". Now, do I have to use a Linux distro to walk through the book, or would OS X be sufficient?
If I need a Linux distro, then would using it through a VM be sufficient or do I need to install it natively?
|
I would highly recommend running Linux in a VM. All the software is available freely to download and there is no practical difference between running in a VM and running natively for the purposes of learning the command line.
Furthermore, Linux command line mostly consists of bash + GNU coreutils, which is very different from BSD Unix (and OS X is a succedessor of BSD Unix). There is a very big difference of preferences in writing arguments in BSD Unix and GNU Linux. You can bite yourself even as non-newbie with different options to standard utilities like ps and tar if you work on both systems.
Using OS X when your book is Linux specific will regularly throw up inconsistencies and differences that will appear superficial when you're more experienced, but will simply be confusing when you're learning. Keep things easy for yourself.
This will also allow you to experiment without the worry of breaking your machine by deleting or changing any important files.
And last, though certainly not least, it will allow you to set up a SSH connection to your VM from your OS X Terminal, so you can get used to using SSH keys, and to the idea that it makes no difference whether your Linux server is a native machine, a local VM, or running out on AWS or Digital Ocean: it all works the same!
| Do I need a Linux distro to learn the command line or would OS X be sufficient? |
1,301,018,892,000 |
Let me explain with an example:
I have a line where I declare an alias in my ~/.bashrc:
> grep lsdir ~/.bashrc
alias lsdir='ls -d */'
I have just added this line to my bashrc, and the alias is thus not yet added to my current session environment. I would also like not to re-source all my bashrc for some configuration reason, which is why I would like to simply run this grepped line on its own.
For the purpose of curiosity and education, I tried to do it without having to write it down manually, to no avail.
I tried this:
> $(grep lsdir ~/.bashrc)
bash: alias: -d: not found
bash: alias: */': not found
or this:
> "$(grep lsdir ~/.bashrc)"
bash: alias lsdir='ls -d */': No such file or directory
or even this:
> $("grep lsdir ~/.bashrc")
bash: grep lsdir ~/.bashrc: No such file or directory
But none worked. Is there any way to achieve this ?
|
I found the answer:
The key is using the builtin eval. Doing this will achieve the wanted behavior (more precisely running the command in the actual shell we're logged in, instead of a subshell):
> eval "$(grep lsdir ~/.bashrc)"
> type lsdir
lsdir is aliased to `ls -d */'
| Is it possible in Bash to run the output of a command as the actual command-line to run |
1,301,018,892,000 |
I have to change a file/directory's ownership using chmod. I know only the owner's username but want to change the default group name simultaneously. At this stage the group name is not decided so I am putting same as the username:
chown -R username:username path_to_dir
Command may run for various systems/users. So my concern is, will Linux always have a pair username(user):username(group) OR at some point this default group_name may give error.
Although I have started to find GID from the user belongs
id username | tr '(=)' ':' | awk -F: '{print $3}
But for knowledge I want to know. Till now analysis of /etc/passwd /etc/groups except few users like "shutdown,halt,sync,operator" all users have listed in groups as well.
EDIT 1:
id -gn username is also good option
|
There is no guarantee that the groupname = username will exist.
The most common scenario is that system administrators use on Linux is creating a new user locally on the system is without an explicit specification for the group, which means that the group will be created by default same as the user name and assign the user to have the default GID to be of the newly created group.
This doesn't mean that another system administrator will follow this procedure and if you throw other naming services into the mix like NIS or LDAP the group assigned to be default will likely not be same as the new GID with groupname same as username.
So you shouldn't rely on the fact that username=groupname
| Will there be always a pair of same UID and GID? |
1,301,018,892,000 |
I wrote a small C library for Linux and FreeBSD, and I'm going to write the documentation for it. I tried to learn more about creating man pages and not found the instructions or descriptions of best practices making man pages for libraries. In particular I'm interested in what section to put man pages of the functions? 3? Maybe there good examples or manuals? Create man pages for each function from the library a bad idea?
|
Manual pages for a library would go in section 3.
For good examples of manual pages, bear in mind that some are written using specific details of groff and/or use specific macros which are not really portable.
There are always some pitfalls in portability of man-pages, since some systems may (or may not) use special features. For instance, in documenting dialog, I have had to keep in mind (and work around) differences in various systems for displaying examples (which are not justified).
Start by reading the relevant sections of man man where it mentions the standard macros, and compare those descriptions for FreeBSD and Linux.
Whether you choose to write one manual page for the library, or separate manual pages for the functions (or groups of functions) depends on how complicated the descriptions of the functions would be:
ncurses has a few hundred functions across several dozen manual pages.
dialog has several dozen functions in one manual page. Others will be sure to show many more examples.
Further reading:
man -- display online manual documentation pages (FreeBSD)
man-pages - conventions for writing Linux man pages
groff_mdoc -- reference for groff's mdoc implementation
HowTo: Create a manpage from scratch. (FreeBSD)
What Is A "Bikeshed"?
| Do I need to write man pages for C library? |
1,301,018,892,000 |
I was trying to move a tar.gz file to /opt directory and accidentally move it /root/opt thinking it was the right place. But there was no /root/opt, so the tar.gz file renamed to opt inside the /root folder.
I renamed it back to the tar.gz file; will my files be messed up? I'm concerned if that would still be fine.
|
Your file will be fine.
Renaming a file will not alter the file's contents in any way whatsoever.
In fact, you would still be able to successfully extract the contents of your compressed tar archive using
tar -xvz -f opt
where opt is the name you accidentally gave the file. Renaming it to its original name would obviously be of help to you for knowing what the file might be.
The name of a file is usually of minor importance on Unix systems. In particular, it is not the filename or the filename suffix ("extension") that determines how a file's contents is interpreted (although some utilities (often GUI applications) may try to second guess file formats based on the filename suffix sometimes).
Further reading:
How are file types known if not from file suffix?
File extensions and association with programs in linux
Why does linux use file extension to decide the default program for opening a file though it's independent of file extensions
| Accidentally renamed tar.gz file to a non tar.gz file, will my file be messed up |
1,301,018,892,000 |
I'm using the timeout function on debian to wait 5 seconds for my script.
Works great but the problem I have is that I need a return value. Like
1 for timeout and
0 for no timeout
How am I going to do this?
Have a look at my code:
timeout 5 /some/local/script/connect_script -x 'status' > output.txt
# here i need the return of timeout
As you see my connect_script -x 'status' returns the status as a string and print it to the screen (probably you can't see this)
Background of this issue is that if the server (for connect_script) is freeze the script does nothing. That's why I need the timeout around that. And when it timeouts I want to restart the server. I can do that, but I have no idea how I can see if its timeout or not...
|
If timeout times out, it exits with status 124; you can check this to determine whether the script timed out or not.
| Timeout function return value |
1,301,018,892,000 |
$ ps aux | grep -i ssh
USER 4364 0.0 0.0 9004 1032 ? Ss 12:20 0:00 ssh -v -fND localhost:4000 USERNAME@SERVER-IP-ADDRESS
$ pgrep localhost:4000
Why doesn't this work?
|
By default, pgrep(1) will only match against the process name. If you want to match against the full command line, use the -f option:
$ pgrep -f localhost:4000
| Why can't I pgrep a process? |
1,301,018,892,000 |
Sometimes I unplug my USB drive only to find out files were not written to it.
I suppose the only way to ensure files are written to it is to right click on the USB drive on the desktop and then select "un-mount", but sometimes I forget.
What is the best way to ensure files are written to the USB drive instantly? This way I can remove the USB drive as soon as I notice the LED light on the USB drive stopped blinking.
OS: CentOS 6
|
This is Gilles' answer, saving it here so it doesn't get lost.
If you use the sync mount option on the removable drive, all writes are written to the disk immediately, so you won't lose data from not-yet-written files. It's a bad idea, but it does what you're asking, kind of.
Note that sync does not guarantee that you won't lose data. Unmounting a removable drive also ensures that no application has a file open. If you don't unmount before unplugging, you won't notice if you have unsaved data until it's too late. Unmounting while a file is open also increases the chance of corruption, both at the filesystem level (the OS may have queued some operations until the file is closed) and at the application level (e.g. if the application puts a lock file, it won't be removed).
Furthermore, sync is bad for the lifetime of the device. Without the sync option, the kernel reorders writes and writes them in batches. With the sync option, the kernel writes every sector in the order requested by the applications. On cheap flash media that doesn't reallocate sectors (meaning pretty much any older USB stick, I don't know if it's still true of recent ones), the repeated writes to the file allocation table on (V)FAT or to the journal on a typical modern filesystem can kill the stick pretty fast.
Therefore I do not recommend using the sync mount option.
On FAT filesystems, you can use the flush mount option. This is intermediate between async (the default) and sync: with the flush option, the kernel flushes all writes as soon as the drive becomes idle, but it does not preserve the order of writes (so e.g. all writes to the FAT are merged).
| How to remove a USB drive without worrying if its been unmounted? [duplicate] |
1,301,018,892,000 |
I want to display the current network utilization (bandwidth usage) of one interface of a Debian box on a website. It is not supposed to be very elaborate or precise, just a simple number such as "52 Mbit/s".
Typical network bandwidth monitors such as iftop give me no way to simply extract such a value.
How can I best retrieve it?
For example, I guess I might parse /proc/net/dev every few minutes. Not sure if this is really the best way to do this though.
|
I think ifstat will help you :
[root@localhost ~]# ifstat -i eth0 -q 1 1
eth0
KB/s in KB/s out
3390.26 69.69
| How should I determine the current network utilization? |
1,301,018,892,000 |
Are there any CLI or GUI functions that I can use to monitor hits to iptables and watch as packets interact with iptables?
|
You should be able to have this enabling modules ipt_LOG ipt6_LOG and using TRACE chain in raw table to debug streams/rules you need.
See http://backreference.org/2010/06/11/iptables-debugging/ for reference
| Debugging iptables using live packet views |
1,301,018,892,000 |
what is the command or how would you make a process into a service in Linux? isn't a service basically a daemon?
|
An example of a user service is the easiest way to describe how to do this.
Let's assume that you have a binary or a script, called mytask, that you want to run as a service, and it is located in /usr/local/bin/.
Create a systemd unit file, called my_example.service, in your home directory, ~/.config/systemd/user/, with the following contents:
[Unit]
Description=[My example task]
[Service]
Type=simple
StandardOutput=journal
ExecStart=/usr/local/bin/mytask
[Install]
WantedBy=default.target
The line ExecStart is the most relevant, as it is in this line that you specify the path to your binary or script that you want to run.
To make your service start automatically upon boot, run
systemctl --user enable my_example.service
If you want to start the service immediately, without rebooting, run
systemctl --user start my_example.service
If you want to stop the service, run
systemctl --user stop my_example.service
To check the status of your service, run
systemctl --user status my_example.service
| How do you make a process a service under systemd? |
1,301,018,892,000 |
I have Windows 10 HOME installed on my system. After I installed Windows 10 HOME, I installed Ubuntu 17.10 on a separate partition so that I could dual boot.
I removed Ubuntu 17.10 by deleting the partition it was installed on. Now I am unable to start my system. At boot, my system stops at the Grub command line.
I want to boot to my Windows 10 installation which I haven't removed from my system.
This is displayed at startup:
GNU GRUB version 2.02 ~beta3-4ubuntu7
minimal BASH-like editing is supported.for the first word, TAB lists
possible commands completions.anywhere else TAB lists the possible device or file completion.
grub>
How can I boot my Windows partition from this grub command?
Laptop :- Toshiba satellite C55 - C5241
|
GRUB uses the contents of /boot/grub/ located on your Linux partition to boot your system normally. Because of this GRUB has very minimal functionality.
If you are on a Legacy BIOS system you're out of luck and you'll need to Windows disk for boot repair. (this is because GRUB can't load its NTFS driver because you deleted it).
If you have a UEFI system which is most likely then you can still load Windows pretty easily.
First type:
chainloader +1
If this says unknown command you're out of luck because GRUB didn't embed this command so you must have deleted it.
If it reboots back to grub prompt then you have a legacy BIOS and you're out of luck.
If it says invalid efi path then you should be able to proceed.
Type:
ls (hd0,gpt1)/
this should return "/efi" Now do:
chainloader (hd0,gpt1)/EFI/Microsoft/Boot/bootmgfw.efi
boot
| How to start windows 10 through grub command line [closed] |
1,301,018,892,000 |
I use tmux to develop, with two panes: one to edit the code, and one to compile it.
I need to switch pane very often to launch the compile command (say "mvn install").
How can I bind a key (say "Ctrl+B C") to launch that specific command in the other pane (or without any pane at all)?
|
C-b c already has a standard binding which it might be wise to leave unchanged. Choosing another character, eg C-b C you can setup a binding in your
~/.tmux.conf file as follows:
bind C send-keys -t.- 'mvn install' Enter
The -t.- means "the other pane". Enter stands for the key of that name, i.e. the newline at the end of the command.
| tmux: how to bind a key to launch shell command? |
1,301,018,892,000 |
mv can't move a directory to a destination with a same-name directory:
$ mv fortran/ imperative_PLs/
mv: cannot move ‘fortran/’ to ‘imperative_PLs/fortran’: Directory not empty
Why does mv not work in this case? Can that be explained from the system calls mv invokes? (Compare to rsync which can)
Why is mv designed to not work in this case? What is the rationale or point?
|
mv doesn't work in this case because it's not been designed to do so. The system calls are (probably) either
Move to same filesystem: rename (originally link and unlink)
Move across filesystems: recursive file copy followed by recursive unlink
Opinion: I think it's not so much that it was designed not to work, as it wasn't designed to handle this use case. For a "simple" tool that's intended to do one thing well you'd need to provide a set of switches to indicate to mv which of these action paths to take:
To bail with an error, as in the current implementation
To merge, bailing with an error if a file already exists
To merge, replacing any target files that already exist
If the merge/replace action is what you want, you can implement it easily enough with cp followed by rm, or by using one of the file tree copying utilities tar, pax, etc.
| Why can't mv deal with existence of same-name directory in destination? |
1,301,018,892,000 |
I am using Bumblebee on OpenSuse 13.1 on my Intel HD4600 / Nvidia GTX 860M combo.
Steam games seems to lag a bit, when using primusrun. (vblank_mode=0 primusrun)
Testing both primusrun and optirun with glxspheres, indicates that optirun is the better option on my system. But my Steam games does not start with the optirun command.
vblank_mode=0 primusrun glxspheres
209.926051 frames/sec - 234.277473 Mpixels/sec
vblank_mode=0 optirun glxspheres
250.734727 frames/sec - 279.819955 Mpixels/sec
Any help would be appreciated.
|
In theory, primusrun is preferred over optirun for performance and stability, as recommended by the bumblebee devs. I'm unsure why you get the results you did. I know in some cases, frames are capped, but that doesn't seem to be the case for you. (In my case I get 150 fps for optirun glxspheres64 and 60 fps for primusrun glxspheres64, which I believe is due to the cap.)
In any case, I use different options for different Steam games. Mostly, performance is similar with different commands, but the main difference to me is stability. This includes stability with and without the Steam overlay enabled. The following are different settings that I've used for different games, which you can test. I generally try this first:
primusrun %command%
However, I've found this is not always optimal. Sometimes optirun is more stable.
optirun %command%
In some cases, neither of those work (e.g. in Team Fortress 2) so I use:
LD_PRELOAD="libpthread.so.0 libGL.so.1" __GL_THREADED_OPTIMIZATIONS=1 optirun %command%
| Is it possible to run Steam games using optirun? |
1,301,018,892,000 |
I have created a script to install two scripts on to the crontab.
#!/bin/bash
sudo crontab -l > mycron
#echo new cron into cron file
echo "*/05 * * * * bash /mnt/md0/capture/delete_old_pcap.sh" >> mycron #schedule the delete script
echo "*/12 * * * * bash /mnt/md0/capture/merge_pcap.sh" >> mycron #schedule the merge script
#install new cron file
crontab mycron
rm mycron
The script runs, and add the two lines to the crontab. But if I run the script again, it adds those lines again , thus I will have four lines saying the same stuff. I want the install script to run such that, the lines inserted to the crontab do not repeat. How can I do that
|
I would recommend using /etc/cron.d over crontab.
You can place files in /etc/cron.d which behave like crontab entries. Though the format is slightly different.
For example
/etc/cron.d/pcap:
*/05 * * * * root bash /mnt/md0/capture/delete_old_pcap.sh
*/12 * * * * root bash /mnt/md0/capture/merge_pcap.sh
The difference in the format is adding the user to run the job as after the time specification.
Now you can simply check if the file exists, and if you overwrite it, it doesn't matter.
Note that it's possible your cron daemon might not have /etc/cron.d. I do not know which cron daemons have it, but vixie cron is the the standard cron daemon on linux, and it does.
| Installing crontab using bash script |
1,301,018,892,000 |
I see all these links explaining packages and .debs... I know that... and there are many kludges to get tar.gz files working (eg: update-alternatives for Java or manually dropping the file in /usr/local/bin (or somewhere else, which I had deduced from hours of searching)). If packages are so smart, how are so few Linux applications available in packages or .debs/rpms?
I'm speaking as a new user; I know experts probably know it better (I think I can download a compilable version of Eclipse?). Like netbeans and chrome are .sh, eclipse is a plain, launchable directory, Java requires this update-alternatives business but I don't think it registers itself into Ubuntu/Debian's "programs list" (just registers as a command), etc. (I know these are sometimes available in repositories, but I'm just confused why download pages don't have proper explanations).
Long story short: If a download or compile a tar.gz file, how do I register it to the system? update-alternatives seems to register it as a command, in Ubuntu, it doesn't show up in the search bar. In Debian, I can manually add a shortcut to the GNOME 2 launcher. But what should I really be doing?
Edit:
So after playing around a bit more with the new solutions, I can sorta refine my "problem":
How should I manage my manually installed programs? Firefox and Eclipse are my only examples so far (I don't download a lot of stuff). They can both run out the box, which I like. Except, where should I be installing them? I see Eclipse has it's own instructions, but I'd rather do all my "manual packages" the same way.
After some research, I decided to put these programs into /usr/local/bin.
From how to install eclipse, I figured to get something to show up in the launcher, I need to put a xxx.desktop file in ~/.local/share/applications/. Does the name of this .desktop file matter?
Stuff with autotools (I look for a configure or unix/configure file) will work out fine. Some research points that I should use CheckInstall to keep track of all these.
I should use update-alternatives to register paths. From this java thread, it looks like I create a link from /usr/bin/java to /usr/lib/jvm/jdk.... When I install these "standalone" applications like Eclipse or Firefox, should I always link to /usr/bin/[app]? And if assertion 1 is true, I would be doing stuff like sudo update-alternatives --install "/usr/bin/[app]" "[app]" "/usr/local/bin/[app]" 1
Are these instructions correct/a good way to manage manual installations? Are there any other steps I should follow? Other suggestions?
|
Why are a lot of apps not available in package repos?
There could be many reasons:
No one bothered to package the app.
No one is allowed to package the app (like Oracle insisting on being the only one to distribute Java).
The package is published under a license that contradicts the distros values.
...
There's no one single reason. If you'd like to see your favorite app in your distro's package manager, you should treat each case separately. Try to get in touch with the devs (on an IRC channel or a mailing list for instance) and ask how you could help packaging.
How to install a tarball?
A tarball (.tar.gz package) could contain anything. Until you actually open it, you have no way of assuming how to install it. Again, each package should be approached differently.
Look for documentation! Any (semi-)decent package will provide instructions on how to install the application. Your first reflex should always be to look for a text file called README, INSTALL or something like this. Checking out the website of the publisher might also help.
Since every package is different, there's no universal way to process every tarball in the world. That's like asking for a recipe which works on all the ingredients in the world. Not happening.
A good knowledge of your system, your distro and your desktop environment will help, so, if this is reassuring, things will look more and more predictable as you spend time in the linux world.
A special case: Autotools
As projects grow bigger, they need to provide easy ways to move from source code to binary to full install on the system. This is why they ship with an embedded build system, a collection of scripts to do the necessary.
In the Linux/Open Source/Free Software world, one build system got a wider adoption: GNU Autotools. If you ever deal with a(n open) source package, there's a solid chance that you'll be using Autotools.
In the simplest case, here's how to install an app packaged with autotools:
./configure: A script that will generate the Makefiles corresponding to your system (it also often checks for the availability of dependencies).
make: Compiling the source code according to the Makefiles generated earlier.
make install: Copies the binaries to the appropriate locations, creates symlinks, and any other step defined by the developer.
Notes
configure scripts usually have a lot of options, like which compiler to use or how to define the target directory. If you need flexibility, it's worth looking at ./configure --help.
Even if you're sure it's Autotools and you know it really well, always start by reading docs (README, INSTALL, ...)
Answer to the update in the question
What you're asking for has no definite answer. Everyone here might have an opinion on what constitutes "good practice", but at the end of the day, only you can find what works for you. If there was an easy answer, you wouldn't be asking the question. Your distro would've answered it for you.
This being said, here're a few personal remarks.
On my system, I reserve /usr/local/bin for the packages installed by my package manager. Everything I compile/install by hand goes in /opt. This is a detail but it helps avoiding major headaches when dealing with several versions of the same program.
xxx.desktop, and GUI issues in general, are specific to the desktop environment you're using. If it works for your system, great. But it cannot be generalized to all the environments available on Unix.
/usr/local/bin has the advantage of already being in your PATH. If you want to use another directory (like /opt as I suggest), be sure to include it in your PATH. If you don't know how to do it, open a terminal and execute the following in a terminal (not the prettiest way to do it, but without knowing anything about your system, I cannot suggest anything else): echo 'export PATH=$PATH:/opt' >> ~/.bashrc
| How to truly install a tar.gz file on Linux - how to manage manually-installed (or standalone) applications? |
1,301,018,892,000 |
Is there any way to make/run a bash script on reboot
(like in Debian/Ubuntu for instance, since thats what my 2 boxes at home have)
Also, any recommended guides for doing cron jobs? I'm completely new to them (but they will be of great use)
|
On Ubuntu/Debian/Centos you can set up a cron job to run @reboot. This runs once at system startup. Use crontab -e to edit the crontab and add a line like the example below e.g.
@reboot /path/to/some/script
There are lots of resources for cron if you look for them. This site has several good examples.
| Bash Script on Startup? (Linux) |
1,301,018,892,000 |
Why do we need the reboot function in different binaries?
shutdown -r
and
reboot
Or do they differ in something?
|
We don't necessarily need them both, but we have them both because of the history of Unix, and its multiplicity of versions.
From their respective man pages:
The shutdown utility appeared in 4.0BSD.
A reboot utility appeared in Version 6 AT&T UNIX.
shutdown is more general-purpose, and more powerful, while reboot is friendlier and easier to remember.
shutdown allows you to specify a temporal argument (to restart in 5 minutes, for instance) and allows you to do many things besides reboot, including:
you can just kick off users and not actually shutdown
you can put the system to sleep instead of shutting down
you can simply shutdown without rebooting (like the halt command)
you can include a custom warning message for users on the system
However, if you just want to reboot the system now, it's easier to type reboot than shutdown -r now.
| Why do we need the reboot function in different binaries? |
1,301,018,892,000 |
I want to create an array in Bash which to contain all active network interfaces.
I have managed to create a for loop printing them but when I try to create the array, it just contains the last lo interface but not the other. This is my code:
#!/bin/bash
for iface in $(ifconfig | cut -d ' ' -f1| tr ':' '\n' | awk NF)
do
printf "$iface%s\n"
declare -a array_test=["$iface"]
done
for i in "${array_test[@]}"; do echo "$i"; done
And this is my output:
eno1
eno2
eno3
lo
[lo]
Also, how can I exclude the lo localhost interface from the array?
|
Here is a solution, assign the list and then add item to it:
#!/bin/bash
array_test=()
for iface in $(ifconfig | cut -d ' ' -f1| tr ':' '\n' | awk NF)
do
printf "$iface\n"
array_test+=("$iface")
done
echo ${array_test[@]}
If you want the output displayed one item per line:
for i in "${array_test[@]}"; do echo "$i"; done
To remove localhost from output:
if [ "$iface" != "lo" ]
then
array_test+=("$iface")
fi
| Create an array with all network interfaces in bash |
1,301,018,892,000 |
The following lsblk command print the disk usage in bytes
lsblk -bio KNAME,TYPE,SIZE,MODEL| grep disk
sda disk 298999349248 AVAGO
sdb disk 1998998994944 AVAGO
sdc disk 1998998994944 AVAGO
sdd disk 1998998994944 AVAGO
sde disk 98998994944 AVAGO
how to print the disks when disk is greater than 300000000000 , by adding after the pipe awk or perl one-liner or else
expected output:
lsblk -bio KNAME,TYPE,SIZE,MODEL| grep disk | ......
sdb disk 1998998994944 AVAGO
sdc disk 1998998994944 AVAGO
sdd disk 1998998994944 AVAGO
|
You can do it with awk itself for pattern matching instead of using grep.
lsblk -bio KNAME,TYPE,SIZE,MODEL| awk '/disk/ && $3> 300000000000 || NR==1'
Or use scientific value 3e11.
| print line only if number in third field is greater than X [duplicate] |
1,301,018,892,000 |
I have a file system for a device I am programming that I would like to make an exact copy of. Ideally I would like this copy to be identical to the folder that it was copied from. I have tried using cp -r cp -a and rsync -azvP to try to achieve this. Each one though results in a folder with different size (using du -s) and ultimately,even though my device runs off of the original folder, it won't run off of the one that I copied.
What is getting left out that the commands I have used aren't accounting for?
Is it possible to keep everything identical when copying a file system/folder? If so how would I go about doing that?
P.S. I posted a similar questions on StackOverflow but quickly realized I had asked it on the wrong exchange
Edit:
This may not be helpful but no matter which method I use the copied directory always causes the machine in question to Kernel Panic with the following output.
VFS: Unable to mount root fs via NFS, trying floppy. VFS: Cannot open
root device "nfs" or unknown-block(2,0) Please append a correct
"root=" boot option; here are the available partitions: 1f00
64 mtdblock0 (driver?) 1f02 64 mtdblock2 (driver?) 1f04
2432 mtdblock4 (driver?) 1f05 128 mtdblock5 (driver?)
1f06 4352 mtdblock6 (driver?) 1f07 204928
mtdblock7 (driver?) 1f08 50304 mtdblock8 (driver?) 0800
8388608 sda driver: sd Kernel panic - not syncing: VFS: Unable to
mount root fs on unknown-block(2,0)
|
I generally use one of the following alternatives:
rsync -aHAX (add v for verbosity) makes sure that you preserve any link structure and x-attrs in the target folder while copying. Don't forget a means archive and preserves time, ownership and permissions already.
Simple tar cvf (don't compress to save time, just tar them up) is what I use if the first one doesn't meet what I need for whatever reason and I have no time, but I always try the first one.
To check that everything went as it should, you can run diff -r <folder1> <folder2> afterwards if you want.
| How can a filesystem be copied exactly as is? |
1,301,018,892,000 |
I'm trying to ping from guest to my host network without success.
qemu-system-x86_64 -hda debian_squeeze_amd64_standard.qcow2 -netdev user,id=user.0 -device e1000,netdev=user.0
I try to ping a random machine:
$ ping 10.0.2.21
Destination Host Unreachable
In the guest I'm only able to ping the host 10.0.2.2 (DHCP server).
|
QEMU supports ICMP on the SLIRP backend. It is necessary to allow so called ping socket (PF_INET, SOCK_DGRAM, PROT_ICMP) for users in kernel.
It is simple
sysctl -w net.ipv4.ping_group_range='0 2147483647'
See also http://lwn.net/Articles/422330/
| QEMU how to ping host network? |
1,301,018,892,000 |
is it possible that a folder like /proc/4587 exists even though there isn't a process that has PID 4587?
|
If /proc is only the proc mount (and no one is playing tricks with overlays), no, a pid-based folder only exists as long as the corresponding process exists in some state (including as a zombie). In fact, just before returning a directory entry for a process id, the kernel re-validates the process’ existence — so at the instant a directory entry is returned, the corresponding process is still there. Accessing a directory also starts by looking up the corresponding process. (If the line numbers change, look for proc_pident_instantiate and proc_pident_lookup.)
You can run into issues caused by listing /proc and using the results later (even a few microseconds later): a process can be running when you list /proc, and stop before you act on the results.
| Can /proc/PID still exist when PID isn't running? |
1,439,378,149,000 |
I have a two text files: string.txt and lengths.txt
String.txt:
abcdefghijklmnopqrstuvwxyz
lengths.txt
5
4
10
7
I want to get the file
>Entry_1
abcde
>Entry_2
fghi
>Entry_3
jklmnopqrs
>Entry_4
tuvwxyz
I'm working with about 28,000 entries and they vary between 200 and 56,000 characters.
At the moment, I'm using:
start=1
end=0
i=0
while read read_l
do
let i=i+1
let end=end+read_l
echo -e ">Entry_$i" >>outfile.txt
echo "$(cut -c$start-$end String.txt)" >>outfile.txt
let start=start+read_l
echo $i
done <lengths.txt
But it's very inefficient. Any better ideas?
|
You can do
{
while read l<&3; do
{
head -c"$l"
echo
} 3<&-
done 3<lengths.txt
} <String.txt
It requires some explanation:
The main idea is to use { head ; } <file and is derived from the underestimated @mikeserv answer. However in this case we need to use many heads, so while loop is introduced and a little bit of tweaking with file descriptors in order to pass to head input from both files (file String.txt as a main file to process and lines from length.txt as an argument to -c option). The idea is that benefit in speed should come from not needing to seek through the String.txt each time a command like head or cut is invoked. The echo is just to print newline after each iteration.
How much it is faster (if any) and adding >Entry_i between lines is left as an exercise.
| Fast method of splitting string from textfile? |
1,439,378,149,000 |
This question is fairly lengthy, so I'll ask the questions at the top and then go through my method of coming to the questions:
Did (Busybox based) rm not execute because there wasn't enough contiguous RAM?
If so, is there a lightweight method of defragging the DMA - without resorting to a system restart?
If not, what caused it? How can I prevent it from happening in the future?
After our test system had been running fairly intensively over the last few days - I telnet'd into the system and checked the test results. When I came to delete some data, the system returned the command line (as if the command had executed correctly). When I came to check the directory for another set of results, I saw the file still existed (using ls).
After this, I noticed more and more of my shell commands wern't performing as expected.
I'll start off with an output from dmesg after rm failed to execute correctly:
Allocation of length 61440 from process 6821 (rm) failed
DMA per-cpu:
CPU 0: hi: 0, btch: 1 usd: 0
Active_anon:0 active_file:1 inactive_anon:0
inactive_file:0 unevictable:6 dirty:0 writeback:0 unstable:0
free:821 slab:353 mapped:0 pagetables:0 bounce:0
DMA free:3284kB min:360kB low:448kB high:540kB active_anon:0kB inactive_anon:0kB active_file:4kB inactive_file:0kB unevictable:24kB present:8128kB pages_scanned:0 all_unreclaimable? no
lowmem_reserve[]: 0 0 0
DMA: 31*4kB 47*8kB 42*16kB 64*32kB 1*64kB 0*128kB 0*256kB 0*512kB 0*1024kB 0*2048kB 0*4096kB = 3284kB
14 total pagecache pages
Unable to allocate RAM for process data, errno 12
Initially, I thought I was unable to run the program in the largest portion of contiguous memory. Meaning the DMA was too fragmented and I would have to find a way of getting the system to defragment the memory.
Then I did a quick math/sanity check and realised that the program should have been able to run in the sole 64kB contiguous memory slot. Rm was requesting 61440 bytes (60kB).
I did a good old "manual defrag" and rebooted the system. When I rebooted the sytem I output /proc/buddyinfo:
Node 0, zone DMA 2 8 3 12 0 1 0 1 0 1 0
Which I suspect map to:
2 x 4 kB
8 x 8 kB
3 x 16 kB
12 x 32 kB
1 x 128 kB
1 x 512 kB
But if one sums the above list of values, it doesn't match up with the output of /proc/meminfo:
MemTotal: 6580 kB
MemFree: 3164 kB
Buffers: 0 kB
Cached: 728 kB
SwapCached: 0 kB
Active: 176 kB
Inactive: 524 kB
Active(anon): 0 kB
Inactive(anon): 0 kB
Active(file): 176 kB
Inactive(file): 524 kB`
Unevictable: 0 kB
Mlocked: 0 kB
MmapCopy: 844 kB
SwapTotal: 0 kB
SwapFree: 0 kB
Dirty: 0 kB
Writeback: 0 kB
AnonPages: 0 kB
Mapped: 0 kB
Slab: 1268 kB
SReclaimable: 196 kB
SUnreclaim: 1072 kB
PageTables: 0 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 3288 kB
Committed_AS: 0 kB
VmallocTotal: 0 kB
VmallocUsed: 0 kB
VmallocChunk: 0 kB
To recap, my questions are:
Did rm not execute because there wasn't enough contiguous RAM?
If so, is there a lightweight method of defragging the DMA - without resorting to a system restart?
If not, what caused it? How can I prevent it from happening in the future?
I am using Lantronix's XPort Pro (8MB, Linux OS) running uClinux version 2.6.30. The shell in use is hush.
|
It's taken a bit of time, but I thought I'd hold off answering until I had answers to all 3 of my sub-questions.
Before I start though, I will mention that the correct term when it comes to "de-fragmenting" working memory is referred to "compacting" working memory.
1. Did rm not execute because there wasn't enough contiguous RAM?
I was correct in my conclusion - rm didn't execute because there was insufficient contiguous RAM. The system had been acquiring RAM and fragmenting it, thus making it unreclaimable.
2. If so, is there a lightweight method of defragging the DMA - without resorting to a system restart?
Turns out there is no way of compacting the memory, short of restarting the embedded system. In the case of a MMU-less system, prevention is the name of the game.
Part of me ponders if its possible to hack the linux kernel to emulate the MMU in software. I figure if it were possible, someone would have done it already. I can't imagine its an entirely new concept ;)
3. How can I prevent it from happening in the future?
For this project, I was using cron to manually initiate the program each time it was required. A much better way to do this is to call the program on start up, and then force the program to sleep until it is required. This way, the memory doesn't need to be allocated on each use. Thus reducing fragmentation.
On the first iteration of the project, we relied on my shell script calls to perform critical functions (such as rm). We didn't see the need in re-inventing the wheel if we didn't need to.
However, I would recommend avoiding the shell where possible for an MMU-less system -
(Question, what happens if you execute ls -la /path/to/directory/ | grep file-i-seek?)
(Answer: it starts a new subprocess)
If you need to implement some of the core shell script functionality in your C program, I recommend checking out the source code used in BusyBox. Chances are you'll be using C in your embedded system..
| Defragging RAM / OOM failure |
1,439,378,149,000 |
Using the command
$ date +%j
gives an output of the day of the year (001-366).
However I need to use the day of the current year as an input format i.e.
$ date --date='066 day' +%F
Which for year 2021 I would expect 2021-03-07 as the output. Instead I get 2021-05-13. Does anyone know what is going on and if there is a way to get what I want using date.
|
To get the 66th day of the year with GNU date:
$ date --date='jan 1 + 65 days' +%F
2021-03-07
or
$ date --date='dec 31 last year + 66 days' +%F
2021-03-07
With date --date='066 day' +%F you get the date 66 days from today. On the 8th of March, this happens to be the 13th of May.
The above uses GNU date. On OpenBSD (not that you asked, but anyway), you could do something like the following:
$ date -u -r "$(( $(date -ju -f %m%d 0101 +%s) + 65*86400 ))" +%F
2021-03-07
which would be somewhat similar to the first GNU date command above in that it adds some time from January 1st.
| Is there a way to use the day of year as an input format for the date command? |
1,439,378,149,000 |
I have a file like this:
AAAA
BBBB
CCCC
DDDD
etc
Words in separate lines. I want to add them quotes using tr.
So I tried the following:
1) To add a quote in the start of each word i.e. 'AAAA
tr '^\w$' '\'\w$' <file.txt Does not work
tr '^\w$' ''\w$' <file.txt Does not work
Both of the above make the command line stuck.
2) To add quote to the end I tried:
tr '\n' ''\n' <file.txt But this does not work and the command line gets stuck.
Why don't these regex work with tr?
|
You can't replace multiple things like this with tr. I would use sed to do this instead.
Example
$ sed "s/^/'/" file.txt
'AAAA
'BBBB
'CCCC
'DDDD
Says to find the beginning of each line (^) and replace it with a single quote (').
If you want to wrap the "words" in single quotes you can use this form of the command:
$ sed "s/\(.*\)/'\1'/" file.txt
'AAAA'
'BBBB'
'CCCC'
'DDDD'
This time we're saving anything on the line in a temporary variable (\1). We then replace the line with this '\1'.
This command can be abbreviated to this, use GNU specific switches:
$ sed -r "s/^(.*)$/'&'/" file.txt
'AAAA'
'BBBB'
'CCCC'
'DDDD'
| Can tr work with regex? |
1,439,378,149,000 |
I accidentally executed the following command on the etc directory:
sudo chmod -R 700 /etc
I know that I have done something very wrong. My terminal now prints:
I have no name!@ubuntu: /$
How can I revert my etc directory to its earlier state?
I tried changing the permissions but it is failing now. Also, it would be very helpful if someone can explain what actually went wrong when I executed that command on etc. It was only file permissions. Then why does the whole system seems completely blown up? Why is it that no login passwords are working now? I know that there is a file in etc directory that has to do with users. But how did changing permissions jeopardize everything? Some technical details about this would be very helpful.
|
One thing went wrong: the use of sudo with that command. The -R switch tells chmod to recursively set the permissions to that directory, which is, in every case, a non-recommended action (should we call it: heresy) if you don't know what are you doing (once this happened to me, I didn't issue the command but a faulty GUI made it, and my system went wire).
It was only file permissions. Then why does the whole system seems completely blown up?
GNU/Linux is very sensitive to file permissions, as it was built with stability and security in mind. Same applies to most programs run in GNU/Linux (i.e. apache2 drops root privileges and uses www-data, or similar user, and your 700 permission wouldn't allow it to read/write it own files).
Why is it that no login passwords are working now?
As you already mention, login passwords are stored in a file in /etc/passwd and only root (I assume you didn't change that) can read it, but the login prompt (or GUI login) uses a non-privilege account, hence it cannot read the file.
But how did changing permissions jeopardize everything?
Same as said above, Linux is very sensitive to file permissions. Some programs even check the permissions of their configuration files and if they are not expected they won't run at all.
How can I revert my etc directory to its earlier state?
If you use a RPM-based distro, this can be done using the rpm --setperms command, it would be painfully reverting one by one the packages, on Debian-like system apt-get --reinstall install is your friend. Other solutions may be available, but would need a working system for it.
| How can I revert a chmod on the etc directory? |
1,439,378,149,000 |
I'm configuring & compiling new 3.0 kernel. One of the goodies I planned to use for some time (by patching) that was merged into 3.0 is zram.
Is it possible to set both hdd swap and zram swap so the zram is used first and only spilled pages are put into actual swap?
|
swapon have -p switch which sets the priority. I can set up:
swapon -p 32767 /dev/zram0
swapon -p 0 /dev/my-lvm-volume/swap
Or in /etc/fstab:
/dev/zram0 none swap sw,pri=32767 0 0
/dev/my-lvm-volume/swap none swap sw,pri=0 0 0
EDIT: Just for a full solution - such line may be helpful as udev rule:
KERNEL=="zram0", ACTION=="add", ATTR{disksize}="1073741824", RUN="/sbin/mkswap /$root/$name"
| How to set up properly zram and swap |
1,439,378,149,000 |
/dev/tcp is often mentioned in many sources, and I think I saw it in Ubuntu not so long ago. Now, in Debian Jessie, I can't find it. The same with /dev/udp.
tomasz@E4200:/dev$ ls
agpgart dm-1 hidraw3 network_latency sda2 tty11 tty24 tty37 tty5 tty62 vcs2 vfio
autofs dm-2 hpet network_throughput sda5 tty12 tty25 tty38 tty50 tty63 vcs3 vga_arbiter
block dm-3 hugepages null sg0 tty13 tty26 tty39 tty51 tty7 vcs4 vhci
bsg dm-4 initctl port shm tty14 tty27 tty4 tty52 tty8 vcs5 vhost-net
btrfs-control dm-5 input ppp snapshot tty15 tty28 tty40 tty53 tty9 vcs6 watchdog
bus dri kmsg psaux snd tty16 tty29 tty41 tty54 ttyS0 vcs7 watchdog0
char fb0 kvm ptmx stderr tty17 tty3 tty42 tty55 ttyS1 vcsa xconsole
console fd log pts stdin tty18 tty30 tty43 tty56 ttyS2 vcsa1 zero
core full loop-control random stdout tty19 tty31 tty44 tty57 ttyS3 vcsa2
cpu fuse mapper rfkill tomas-vg tty2 tty32 tty45 tty58 uhid vcsa3
cpu_dma_latency fw0 mcelog rtc tty tty20 tty33 tty46 tty59 uinput vcsa4
cuse hidraw0 mem rtc0 tty0 tty21 tty34 tty47 tty6 urandom vcsa5
disk hidraw1 mqueue sda tty1 tty22 tty35 tty48 tty60 vcs vcsa6
dm-0 hidraw2 net sda1 tty10 tty23 tty36 tty49 tty61 vcs1 vcsa7
Has it moved somewhere? (And why?) Does this apply to all Linuxes?
To make it complete, I'm on:
Linux E4200 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt25-2+deb8u3 (2016-07-02) x86_64 GNU/Linux
UPDATE
/dev/tcp not found doesn't answer my question.
This answer:
When you used /dev/tcp/74.125.225.19/80 in a pipe, bash attempted to
run a command named /dev/tcp/74.125.225.19/80 and reported an error
because that file didn't exist.
doesn't tell me much about /dev/tcp. Neither the Redirections section linked.
I gather from the first answer to my question that /dev/tcp is a "virtual" folder. Please post a link that explains this. And if you know, please answer if this has always been so.
|
/dev/{tcp,udp} are only bash internals.
The tcp and udp sockets stored in /proc/net/{tcp,udp} by kernel
| Where has /dev/tcp gone? [duplicate] |
1,439,378,149,000 |
I have a perplexing problem. I have a library which uses sg for executing customized CDBs. There are a couple of systems which routinely have issues with memory allocation in sg. Usually, the sg driver has a hard limit of around 4mb, but we're seeing it on these few systems with ~2.3mb requests. That is, the CDBs are preparing to allocate for a 2.3mb transfer. There shouldn't be any issue here: 2.3 < 4.0.
Now, the profile of the machine. It is a 64 bit CPU but runs CentOS 6.0 32-bit (I didn't build them nor do I have anything to do with this decision). The kernel version for this CentOS distro is 2.6.32. They have 16gb of RAM.
Here is what the memory usage looks like on the system (though, because this error occurs during automated testing, I have not verified yet if this reflects the state when this errno is returned from sg).
top - 00:54:46 up 5 days, 22:05, 1 user, load average: 0.00, 0.01, 0.21
Tasks: 297 total, 1 running, 296 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.0%us, 0.0%sy, 0.0%ni,100.0%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 15888480k total, 9460408k used, 6428072k free, 258280k buffers
Swap: 4194296k total, 0k used, 4194296k free, 8497424k cached
I found this article from Linux Journal which is about allocating memory in the kernel. The article is dated but does seem to pertain to 2.6 (some comments about the author at the head). The article mentions that the kernel is limited to about 1gb of memory (though it's not entirely clear from the text if that 1gb each for physical and virtual or total). I'm wondering if this is an accurate statement for 2.6.32. Ultimately, I'm wondering if these systems are hitting this limit.
Though this isn't really an answer to my problem, I'm wondering about the veracity of the claim for 2.6.32. So then, what is the actual limit of memory for the kernel? This may need to be a consideration for troubleshooting. Any other suggestions are welcome. What makes this so baffling is that these systems are identical to many others which do not show this same problem.
|
The 1 GiB limit for Linux kernel memory in a 32-bit system is a consequence of 32-bit addressing, and it's a pretty stiff limit. It's not impossible to change, but it's there for a very good reason; changing it has consequences.
Let's take the wayback machine to the early 1990s, when Linux was being created. Back in those days, we'd have arguments about whether Linux could be made to run in 2 MiB of RAM or if it really needed 4 whole MiB. Of course, the high-end snobs were all sneering at us, with their 16 MiB monster servers.
What does that amusing little vignette have to do with anything? In that world, it's easy to make decisions about how to divide up the 4 GiB address space you get from simple 32-bit addressing. Some OSes just split it in half, treating the top bit of the address as the "kernel flag": addresses 0 to 231-1 had the top bit cleared, and were for user space code, and addresses 231 through 232-1 had the top bit set, and were for the kernel. You could just look at the address and tell: 0x80000000 and up, it's kernel-space, otherwise it's user-space.
As PC memory sizes ballooned toward that 4 GiB memory limit, this simple 2/2 split started to become a problem. User space and kernel space both had good claims on lots of RAM, but since our purpose in having a computer is generally to run user programs, rather than to run kernels, OSes started playing around with the user/kernel divide. The 3/1 split is a common compromise.
As to your question about physical vs virtual, it actually doesn't matter. Technically speaking, it's a virtual memory limit, but that's just because Linux is a VM-based OS. Installing 32 GiB of physical RAM won't change anything, nor will it help to swapon a 32 GiB swap partition. No matter what you do, a 32-bit Linux kernel will never be able to address more than 4 GiB simultaneously.
(Yes, I know about PAE. Now that 64-bit OSes are finally taking over, I hope we can start forgetting that nasty hack. I don't believe it can help you in this case anyway.)
The bottom line is that if you're running into the 1 GiB kernel VM limit, you can rebuild the kernel with a 2/2 split, but that directly impacts user space programs.
64-bit really is the right answer.
| memory limit of the Linux kernel |
1,439,378,149,000 |
I'm studying ACLs and am confused on where this information technically resides. Is this just technically just meta data from inodes?
|
The exact details may depend on the filesystem, but conceptually, yes, the ACLs are metadata stored in the file inodes just like traditional permissions, dates, etc.
Since the size of ACLs can vary, they may end up being stored in separate blocks. However the details only matter if you're designing a filesystem or programming a filesystem driver.
| Where is ACL data technically stored? |
1,439,378,149,000 |
man ssh says:
SSH_ASKPASS
If ssh needs a passphrase, it will read the passphrase from the
current terminal if it was run from a terminal. If ssh does not
have a terminal associated with it but DISPLAY and SSH_ASKPASS
are set, it will execute the program specified by SSH_ASKPASS
and open an X11 window to read the passphrase.
I'd like SSH to use an askpass program even if it was run from a terminal.
On occasion, I have to connect to servers, where there's some delay in showing a password prompt (maybe due to network issues, maybe due to attempted reverse DNS lookups, …). I get annoyed and switch to something else, and forget about the attempted connection. (Insert joke about attention span of a goldfish.) When I finally get back to it, the prompt's timed out and even a correct password would just result in a closed connection.
Keys would be one solution, but not every system I use has my usual SSH keys. However, I usually use Ubuntu systems, and Ubuntu has an SSH askpass program installed by default.
If an askpass window popped up, however, I'd be immediately aware of it. That's a good enough compromise for me, if only I can get it to work.
|
This will be a bit more complicated, but combination of several pieces will make it working:
Explanation
To force ssh to use $SSH_ASKPASS program, you can't allow ssh to see the real tty. It is just condition. This can be done by using setsid and using -n switch to ssh.
This case would initiate connection, but you would not be able to interact with the shell, which is probably also your requirement ;) (and also breaks your local TTY).
But you can give up the "first session". You should also add -N switch, which will suppress the remote command and will do just the authentication.
Also the possible output "junk" can be redirected to &> /dev/null if you are not interested in it.
Set up ControlMaster in ssh_config. It is cool feature and once the connection is established, you can "fire up" sessions pretty fast. This snippet in ~/.ssh/config should do that:
ControlPath ~/.ssh/controlmasters/%r@%h:%p
ControlMaster auto
ControlPersist 5m
You can add that into some host block listing your "slow candidates", or just everywhere. It is almost no overhead.
Final line
Then you should be able to connect in this way to the host you expect it will take a while:
setsid ssh -nN host
# wait, insert password in the X11 prompt
ssh host
# will bring you directly to your session
Whole process might be simplified by alias or bash function doing both in one step, but it is left on readers imagination.
Only command-line arguments
You can join both things together on command-line without ssh_config part:
setsid ssh -nNMS ~/.ssh/masters/%C host
# wait, insert password in the X11 prompt
ssh -S ~/.ssh/masters/%C host
# will bring you directly to your session
The following function should work when SSH options aren't specified:
ssh() {
if ! command ssh -o PasswordAuthentication=no "$1" true
then
setsid -w ssh -fnN "$1"
fi
command ssh "$@"
}
-f instructs SSH to go to the background just before program execution, which is after it has got the password.
-w tells setsid to wait for the program to end. In this case, that happens when SSH goes to the background. Combined with ssh -f, the manual wait between the two SSH commands can be eliminated.
The function assumes the first argument is the hostname.
The test is just to prevent unnecessary SSH connections.
| Can I get SSH to use an askpass program even if it was run from a terminal? |
1,439,378,149,000 |
I believe, that once I made sure my cache device state is "clean":
$ sudo cat /sys/block/bcache0/bcache/state
I can just physically remove it from the machine when it is powered off or boot with liveCD and clean the superblock with:
$ sudo dd if=/dev/zero of=<backing device for cache> bs=1024 count=1024
But I cannot find anywhere a confirmation, that this procedure wouldn't mess anything up.
|
Suppose you've set up successfully a bcache, you are already working on it, put there a lot of important data too big to simply backup and start over, when you realized, that you'd better replace the caching device. This is how you can do it. This solution is based on a VM trials.
Lets say we are talking about the device /dev/bcache0, the new cache device is /dev/sdf1 and the backing device is /dev/md1. All commands done by root.
Make sure that nothing is using that bcache0 device.
Do in any order
Remove the cache device just as Martin von Wittich wrote, by echoing setUUID into /sys/block/bcache0/bcache/detach. If you want to repartition the caching device, you need to reboot, because bcache still locks the partitions unless you unregister it.
format- new cache device with make-bcache -C /dev/sdf1 and take a note of the setUUID of that device.
Register our backing device with the new cache set:
echo [setUUID of new cache device] >/sys/block/bcache0/bcache/attach
No need to reboot.
| How do I remove the cache device from bcache? |
1,439,378,149,000 |
Beside our internal IT infrastructure, we've got around 500 Linux machines hosting our services for the on-line world. They are grouped in a bunch of clusters like Database A-n, Product A-n, NFS, Backoffice and so on. Furthermore, they are administered by an external provider, according to our specifications and requirements.
However, we face a lot of trouble during (web-) software development, roll-out and deploy - especially because the dev- and staging-environments have almost nothing in common with the live systems (I spare out the nasty details..).
Thus, I've tried to create virtual machines, copied the various live-systems as exactly as possible and prepared them to connect to e.g. the development-databases instead of the "real" ones transparently for developers (they aren't root). This works pretty well, but...
I was wondering how one could administer those systems remotely and in bulk? Is there some software family I'm not aware of? Or, at least, some techniques or principles one should be familiar with?
We would provide every developer with a bunch of images to be run locally (VirtualBox). The QA dept. would get virtual clusters (XEN or Hyper-V). If I need to provide an additional server-module, re-route a new database connection or just want to update everything provided by the package manager... how could I possibly do that without being forced to log on to every system and/or ask my colleagues to download and run some fixture-script?
I believe there are plenty of solutions. Well, somehow I'm too stupid to enter the correct keywords into the search engines... Or isn't this issue as trivial as it sounds?
For the record:
Almost all systems are running Debian GNU/Linux 6.x "squeeze"
No developer is forced to use a particular OS at his/her workstation
The budget is limited, of course, but not too small to buy proprietary software
A solution that would involve our aforementioned provider is preferred
|
It depends what exactly you need and what you are looking for. But in general there exists multiple solutions for "configuration management like:
puppet
chef
cfengine
ansible
salt
etc. I personally would recommend puppet as it has a big community and a lot of external provided recipes. This allows you to configure and manage systems automatically. If you combine this with own repositories and automated updates via e.g. unattended-upgrades you can automatically update the system.
Another solution is just to provide your own packages like company-base etc. which automatically depends on the necessary software and can configure your system automatically.
You should also look into automates deployments (barebone and virtualized). If you combine this with configuration management or your own repository you can easily automate and reinstall your systems. If you want to get started with automated installation have a look at theforman which supports libvirt as well as bare bone installations and has integrated puppet support. If you want do do it yourself you can look into kickstart (redhat et. al.) or "preseeding" to automatically configure your system. For Debian you can also use something like debootstrap or a wrapper named grml-debootstrap supporting virtualized images.
To help providing the VirtualBox images for your developer have a look at vagrant it allows you to automate the creation of virtualized systems with VirtualBox supporting chef, puppet and shell scripts to customize your virtual environment.
If you want to use the solution by your existing provider you should ask them how they manage your systems but it will probably be some kind of configuration managment. It may be possible to run their agent on your systems if you can access the configuration server.
For google keywords look into devops, configuration management, it automation and server orchestration.
In short automate as much as possible and don't even think about doing stuff manual.
| Linux Bulk/Remote Administration |
1,439,378,149,000 |
I have 3 SATA devices on my system. They show up under /proc/scsi/scsi, although these are not SCSI devices. Why do my SATA devices show up under the SCSI directory?
$ cat /proc/scsi/scsi
Attached devices:
Host: scsi0 Channel: 00 Id: 00 Lun: 00
Vendor: ATA Model: WDC WD2500AAJS-6 Rev: 01.0
Type: Direct-Access ANSI SCSI revision: 05
Host: scsi1 Channel: 00 Id: 00 Lun: 00
Vendor: TSSTcorp Model: CDDVDW TS-H653Z Rev: 4303
Type: CD-ROM ANSI SCSI revision: 05
Host: scsi4 Channel: 00 Id: 00 Lun: 00
Vendor: ATA Model: ST3320620AS Rev: 3.AA
Type: Direct-Access ANSI SCSI revision: 05
|
They show up as SCSI devices because the drivers speak SCSI to the next kernel layer (the generic disk driver). This isn't actually true of all SATA drivers on all kernel versions with all kernel compile-time configurations, but it's common. Even PATA devices can appear as SCSI at that level (again, that depends on the kernel version and kernel compile-time configuration, as well as whether the ide-scsi module is used).
It doesn't really matter whether the driver speaks SCSI to the physical device. Often, it does. ATAPI, used for talking to PATA/SATA optical drives and other devices, is a SCSI-based protocol encapsulation. However, PATA/SATA disks don't use ATAPI. The libata set of drivers also includes a translator between the ATA command set and SCSI so that you can place PATA/SATA disks under the umbrella of the SCSI subsystem. The separate ide interface inside the kernel is more of a historical survivance.
You'll notice that USB disks also appear as SCSI, for the same reason (and they speak SCSI too on the USB bus). The same goes for Firewire.
| Why do my SATA devices show up under /proc/scsi/scsi? |
1,439,378,149,000 |
My server runs out of memory even though there is swap available.
Why?
I can reproduce it this way:
eat_20GB_RAM() {
perl -e '$a="c"x10000000000;print "OK\n";sleep 10000';
}
export -f eat_20GB_RAM
parallel -j0 eat_20GB_RAM ::: {1..25} &
When that stabilizes (i.e. all processes reach sleep) I run a few more:
parallel --delay 5 -j0 eat_20GB_RAM ::: {1..25} &
When that stabilizes (i.e. all processes reach sleep) around 800 GB RAM/swap is used:
$ free -m
total used free shared buff/cache available
Mem: 515966 440676 74514 1 775 73392
Swap: 1256720 341124 915596
When I run a few more:
parallel --delay 15 -j0 eat_20GB_RAM ::: {1..50} &
I start to get:
Out of memory!
even though there is clearly swap available.
$ free
total used free shared buff/cache available
Mem: 528349276 518336524 7675784 14128 2336968 7316984
Swap: 1286882284 1017746244 269136040
Why?
$ cat /proc/meminfo
MemTotal: 528349276 kB
MemFree: 7647352 kB
MemAvailable: 7281164 kB
Buffers: 70616 kB
Cached: 1503044 kB
SwapCached: 10404 kB
Active: 476833404 kB
Inactive: 20837620 kB
Active(anon): 476445828 kB
Inactive(anon): 19673864 kB
Active(file): 387576 kB
Inactive(file): 1163756 kB
Unevictable: 18776 kB
Mlocked: 18776 kB
SwapTotal: 1286882284 kB
SwapFree: 269134804 kB
Dirty: 0 kB
Writeback: 0 kB
AnonPages: 496106244 kB
Mapped: 190524 kB
Shmem: 14128 kB
KReclaimable: 753204 kB
Slab: 15772584 kB
SReclaimable: 753204 kB
SUnreclaim: 15019380 kB
KernelStack: 46640 kB
PageTables: 3081488 kB
NFS_Unstable: 0 kB
Bounce: 0 kB
WritebackTmp: 0 kB
CommitLimit: 1551056920 kB
Committed_AS: 1549560424 kB
VmallocTotal: 34359738367 kB
VmallocUsed: 1682132 kB
VmallocChunk: 0 kB
Percpu: 202752 kB
HardwareCorrupted: 0 kB
AnonHugePages: 0 kB
ShmemHugePages: 0 kB
ShmemPmdMapped: 0 kB
FileHugePages: 0 kB
FilePmdMapped: 0 kB
CmaTotal: 0 kB
CmaFree: 0 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
Hugetlb: 0 kB
DirectMap4k: 12251620 kB
DirectMap2M: 522496000 kB
DirectMap1G: 3145728 kB
|
In /proc/meminfo you find:
CommitLimit: 1551056920 kB
Committed_AS: 1549560424 kB
So you are at the commit limit.
If you have disabled overcommiting of memory (to avoid the OOM-killer) by:
echo 2 > /proc/sys/vm/overcommit_memory
Then the commit limit is computed as:
2 - Don't overcommit. The total address space commit
for the system is not permitted to exceed swap + a
configurable amount (default is 50%) of physical RAM.
Depending on the amount you use, in most situations
this means a process will not be killed while accessing
pages but will receive errors on memory allocation as
appropriate.
(From: https://www.kernel.org/doc/Documentation/vm/overcommit-accounting)
You can use the full memory by:
echo 100 > /proc/sys/vm/overcommit_ratio
Then you will get out-of-memory when physical RAM and swap is all reserved.
The name overcommit_ratio is in this case a bit misleading: You are not overcommitting anything.
Even with this setup you may see out-of-memory before swap is exhausted. malloc.c:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <unistd.h>
void main(int argc, char **argv) {
long bytes, sleep_sec;
if(argc != 3) {
printf("Usage: malloc bytes sleep_sec\n");
exit(1);
}
sscanf(argv[1],"%ld",&bytes);
sscanf(argv[2],"%ld",&sleep_sec);
printf("Bytes: %ld Sleep: %ld\n",bytes,sleep_sec);
if(malloc(bytes)) {
sleep(sleep_sec);
} else {
printf("Out of memory\n");
exit(1);
}
}
Compile as:
gcc -o malloc malloc.c
Run as (reserve 1 GB for 10 seconds):
./malloc 1073741824 10
If you run this you may see OOM even though there is swap free:
# Plenty of ram+swap free before we start
$ free -m
total used free shared buff/cache available
Mem: 515966 2824 512361 16 780 511234
Swap: 1256720 0 1256720
# Reserve 1.8 TB
$ ./malloc 1800000000000 100 &
Bytes: 1800000000000 Sleep: 100
# It looks as if there is plenty of ram+swap free
$ free -m
total used free shared buff/cache available
Mem: 515966 2824 512361 16 780 511234
Swap: 1256720 0 1256720
# But there isn't: It is all reserved (just not used yet)
$ cat /proc/meminfo |grep omm
CommitLimit: 1815231560 kB
Committed_AS: 1761680484 kB
# Thus this fails (as you would expect)
$ ./malloc 180000000000 100
Bytes: 180000000000 Sleep: 100
Out of memory
So while free in practice often will do The Right Thing, looking at CommitLimit and Committed_AS seems to be more bullet-proof.
| Out of memory, but swap available |
1,439,378,149,000 |
Operating System Concepts and APUE say
With vfork(), the parent process
is suspended, and the child process uses the address space of the parent.
Because vfork() does not use copy-on-write, if the child process changes
any pages of the parent’s address space, the altered pages will be visible to the
parent once it resumes. Therefore, vfork() must be used with caution to ensure
that the child process does not modify the address space of the parent.
vfork()
is intended to be used when the child process calls exec() or exit() immediately after
creation.
How shall I understand the last sentence?
When a child process created by vfork() calls exec(), doesn't exec() modify the address space of the parent process, by loading the new program?
When a child process created by vfork() calls exit(), does exit() not modify the address space of the parent process when terminating the child?
I have preference to Linux.
Thanks.
|
When a child process created by vfork() calls exec(), doesn't exec() modify the address space of the parent process, by loading the new program?
No, exec() provides a new address space for the new program; it doesn’t modify the parent address space. See for example the discussion of the exec functions in POSIX, and the Linux execve() manpage.
When a child process created by vfork() calls exit(), does exit() not modify the address space of the parent process when terminating the child?
Plain exit() might – it runs exit hooks installed by the running program (including its libraries). vfork() is more restrictive; thus, on Linux, it mandates the use of _exit() which doesn’t call the C library’s clean-up functions.
vfork() turned out to be quite difficult to get right; it’s been removed in current versions of the POSIX standard, and posix_spawn() should be used instead.
However, unless you really know what you’re doing, you should not use either vfork() or posix_spawn(); stick to good old fork() and exec().
The Linux manpage linked above provides more context:
However, in the bad old days a fork(2)
would require making a complete copy of the caller's data space,
often needlessly, since usually immediately afterward an exec(3) is
done. Thus, for greater efficiency, BSD introduced the vfork()
system call, which did not fully copy the address space of the parent
process, but borrowed the parent's memory and thread of control until
a call to execve(2) or an exit occurred. The parent process was
suspended while the child was using its resources. The use of
vfork() was tricky: for example, not modifying data in the parent
process depended on knowing which variables were held in a register.
| Why is vfork() intended to be used when the child process calls exec() or exit() immediately after creation? |
1,439,378,149,000 |
I'm using Fedora 24 and I have two partitions. I login as user and mount the second partition by clicking on it on the file manager. A window pops up asking for my password so I'm assuming the mount is performed as root.
However, all the files in the mounted partition have user as the owner, and chown doesn't work on them.
[root@mypc Downloads]# chown root:root pointer2.txt
[root@mypc Downloads]# ls -la pointer2.txt
-rwxrwxrwx. 1 user user 945 Aug 2 2016 pointer2.txt
What is the problem here? Is this normal? Can it be fixed?
Here is the relevant output of cat /proc/mounts (line break added for clarity):
/dev/sda2 /run/media/user/666EF0326EEFF8A7 fuseblk rw,nosuid,nodev,relatime,user_id=0,
group_id=0,default_permissions,allow_other,blksize=4096 0 0
|
The partition has a non-Unix file system without support for Unix permissions.
The fuse layer decides to give all files 0777 permissions and assigns the user and group of the user who mounted the filesystem to them.
You will not be able to change the permissions or ownership of these files for as long as they reside on that partition.
| chown not working in mounted partition |
1,439,378,149,000 |
I'm running Awesome WM on the latest Arch Linux with Gnome Terminal and the default bash. I've managed to get this working, but I wonder if any form of improvement is possible with this implementation. The question does NOT relate to opening new tabs, only to spawning new terminal windows with Awesome WM.
I have rewritten the "cd" command to save the current working directory in the ".cd_extend" file:
~/.bashrc
alias cd='source ~/.cd_extend'
~/.cd_extend
#!/bin/bash
command cd $1
echo $(pwd) > ~/.terminal_directory
When I spawn a new terminal, the ".terminal_directory" is read and appended as an argument to gnome terminal's "--working-directory" flag.
~/.dotfiles/open_terminal.sh
#!/bin/bash
DIR=$(cat ~/.terminal_directory)
gnome-terminal --working-directory=$DIR
awesomewm rc.lua
terminal = "~/.dotfiles/open_terminal.sh"
awful.key({ modkey, }, "Return", function () awful.util.spawn(terminal) end)
I wonder if I have missed any internal bash functionality which could have simplified this and if there is room for improvement.
|
After a few days of testing and asking around, this seems to be the easiest implementation. It could be done with a global state which Awesome WM reads, however to keep predictability and ease of implementation I'm keeping this.
~/.bashrc
function cd {
command cd "$1"
pwd > /tmp/terminal_pwd
}
Afterwards I can open the terminal, which reads from the /tmp/terminal_pwd file and opens a new gnome shell with the given working directory.
Awesome WM - rc.lua
-- Terminal
awful.key({ modkey, }, 'Return',
function()
awful.spawn.easy_async_with_shell(
"if [[ -s /tmp/terminal_pwd ]]; then cat /tmp/terminal_pwd; else echo '~'; fi",
function(path)
awful.spawn.easy_async_with_shell('gnome-terminal --working-directory '..path, function() end)
end)
end),
| Spawn new terminal window with the same directory as the previous window |
1,439,378,149,000 |
I'm dealing with an embedded device running Linux. The manufacturers of this device have it set up so that it loads the root filesystem as readonly.
From /etc/mtab:
rootfs / rootfs rw 0 0
/dev/root / squashfs ro,relatime 0 0
This means that I'm unable to modify any files within /etc, such as to add a new user.
I've tried remounting the root directory:
mount -o remount,rw -t squashfs /dev/root /
but I just get an error
mount: cannot remount block device /dev/root read-write, is write-protected
I looked up this error and people were saying to use blockdev. The system doesn't have blockdev installed, so I cross compiled it and copied it across. Then I ran
blockdev --setrw rootfs
but again I got an error:
blockdev: cannot open rootfs: No such file or directory
Is it possible to make /etc writeable if it's not already? I have root access to the system, but I'm not able to access the filesystem 'offline', all changes have to be done via Bash commands.
|
squashfs is a read-only compressed file system. It has no provision to make modification to it once it's been created. So you couldn't write to it even if the underlying block device could be made writeable. You'd need to create a new squashfs image of the whole filesystem with your modifications and burn it to the storage device where that file system is stored, which would be problematic to do from the live system.
Another option is to mount a different file system on /etc. It could be via a union mount if supported by the kernel, which merges two file systems together typically with one file system recording only the changes to a base read-only file system.
Check for support for AUFS_FS or OVERLAY_FS in the kernel config.
For instance to union-mount a directory in /tmp (hopefully writeable though possibly on tmpfs in memory (so not persistent across a reboot) in your case if the system has no permanent writeable storage)
mkdir -p /tmp/etc/work /tmp/etc/upper
mount -t overlay \
-o lowerdir=/etc,upperdir=/tmp/etc/upper,workdir=/tmp/etc/work \
overlay /etc
Then /etc will be writeable and modifications you make to it will actually be stored in /tmp/etc/upper.
Alternatively, if it's only a few file you want to modify, you could bind-mount them (yes you can mount on any file, not only directories) from a version stored in a writable file systems:
cp /etc/passwd /tmp
mount --bind /tmp/passwd /etc/passwd
Then /etc/passwd would be writeable. Of course you can also do that for the whole of /etc instead. (cp -a /etc /tmp && mount --bind /tmp/etc /etc).
| Make readonly /etc writeable |
1,439,378,149,000 |
The situation is this - There is one script on the server which make ping to somewhere and I don't know to where. I want to see to which machine is this ping make and why is returning FAILED.
What I make is to turn tcpdump in one terminal and at the same time turning the script which make ping in second terminal but I'm not sure that is capturing the actual ping.
This is the command I use
tcpdump -w - | tee ping.pcap | tcpdump -r -
Is this the right way of doing this or there is other way?
Edit:
The problem is that when I start tcpdump there is a lot of traffic and I can't recognize which one is from this ping...
|
Try:
tcpdump -i eth0 icmp
which will list ping traffic on interface eth0.
| Ping and tcpdump at the same time |
1,439,378,149,000 |
I know Linux supports multiple users being logged in at the same time.
But what's the maximum number of users that can be logged into Linux at the same time?
I see there are there are 69 tty files (ttyn or ttysn, where n is an integer, such as tty0, tty1, tty2... ) in my /dev directory. I assume that these files are the shells. So I am thinking that this Linux system will support only 69 user logged in simultaneously.
Is my thinking correct? If my assumption is wrong, please explain the users limit of Linux, including how it's implemented.
Also, how do I access the details of already logged in users? I know commands w, who, but I am looking for sophisticated tools.
|
When logging in using SSH, you use a pseudo-terminal (a pty) allocated to the SSH daemon, not a real one (a tty). Pseudo-terminals are created and destroyed as needed. You can find the number of ptys allowed to be allocated at one time at /proc/sys/kernel/pty/max, and this value can be modified using the kernel.pty.max sysctl variable. Assuming that no other ptys are in use, that would be your limit.
w, who, and users are the canonical tools for accessing information about logged in users. last and lastlog also contain historical data.
| How many users does Linux support being logged in at the same time via SSH? |
1,439,378,149,000 |
In Ubuntu, how can I check what information is being sent through the network connection, what programs are doing it, and what sites is my computer connecting to?
I am not paranoid about security, but who knows?
|
I would recommend iptraf or
iftop if you don't need that much
functionality. From the iptraf homepage:
IPTraf is a console-based network statistics utility for Linux. It gathers a variety of figures such as TCP connection packet and byte counts, interface statistics and activity indicators, TCP/UDP traffic breakdowns, and LAN station packet and byte counts.
Features
An IP traffic monitor that shows information on the IP traffic passing over your network. Includes TCP flag information, packet and byte counts, ICMP details, OSPF packet types.
General and detailed interface statistics showing IP, TCP, UDP, ICMP, non-IP and other IP packet counts, IP checksum errors, interface activity, packet size counts.
A TCP and UDP service monitor showing counts of incoming and outgoing packets for common TCP and UDP application ports
A LAN statistics module that discovers active hosts and shows statistics showing the data activity on them
TCP, UDP, and other protocol display filters, allowing you to view only traffic you're interested in.
Logging
Supports Ethernet, FDDI, ISDN, SLIP, PPP, and loopback interface types.
Utilizes the built-in raw socket interface of the Linux kernel, allowing it to be used over a wide range of supported network cards.
Full-screen, menu-driven operation.
Screenshot of the iptraf main menu:
This is a screenshot if iftop:
| Check outgoing network traffic |
1,439,378,149,000 |
I was using a small Linux distro that was running X11 with JWM as its window manager. I was browsing a directory when all of a sudden the mouse froze and the keyboard became unresponsive. The caps lock and scroll lock lights are flashing.
What does this mean... and is there anything I can do about it?
|
The kernel has crashed your pc, the reason could be anything...
Good question is how you collect the crash data, so you know what crashed it.
But the only thing to do is to reboot the pc.
| The caps lock and scroll lock lights are flashing and everything is frozen |
1,439,378,149,000 |
My system timezone is Asia/Tehran, and it has DST changes adjusts in Summer (spring forward) and fall back in Winter; however I do need to disable these DST adjustments and keep timezone always in UTC+3:30. how do I do that in Linux?
|
Part1: Update timeZone for the OS
From 22-September 2022 onwards, Iran will abolish DST and observe standard time year-round. The first official package with these updates are came in "tzdata2022b.tar.gz" package by IANA, therefore here is the way how to apply region Asia/Tehran timeZone updates from it.
Download the package tzdata2022b.tar.gz and decompress it; see All Packages here if you want to get the latest package to apply.
$ tar -xzvf tzdata2022b.tar.gz
Compile to apply the updates for the region(s) of interest (Asia) the system's time zone data through the 'zic' (timezone compiler) command (you should be root/root-privileged user):
# zic asia
Note: the changes will be applied on the Asia/Tehran directly as well as other regions in Asia.
Verify that the updates are applied correctly with the following command and DST is disabled (Note that after 'Wed Sep 21 23:59:59' (Fallback to +0330 as Iran Standard Time) and date afterwards no DST adjusts will be happened):
# zdump -v -c2022,2029 Asia/Tehran
Asia/Tehran -9223372036854775808 = NULL
Asia/Tehran -9223372036854689408 = NULL
Asia/Tehran Mon Mar 21 20:29:59 2022 UTC = Mon Mar 21 23:59:59 2022 +0330 isdst=0
Asia/Tehran Mon Mar 21 20:30:00 2022 UTC = Tue Mar 22 01:00:00 2022 +0430 isdst=1
Asia/Tehran Wed Sep 21 19:29:59 2022 UTC = Wed Sep 21 23:59:59 2022 +0430 isdst=1
Asia/Tehran Wed Sep 21 19:30:00 2022 UTC = Wed Sep 21 23:00:00 2022 +0330 isdst=0
Asia/Tehran 9223372036854689407 = NULL
Asia/Tehran 9223372036854775807 = NULL
Relink the localtime /etc/localtime with the corrected timeZone information using the following command:
# zic -l Asia/Tehran
Verify that date and hwclock are reporting correct date &time.
Below is the solution how to build and apply a specific country timeZone updates only (Asia/Tehran in this answer).
Create a custom ZONE file called Tehran_timeZone and add below Zone information (Rules and Zone information each country can be found in the relevant region file in the tzdata2022b.tar.gz package):
$ cat Tehran_timeZone
# Rule NAME FROM TO - IN ON AT SAVE LETTER/S
Rule Iran 1910 only - Jan 1 00:00 0 -
Rule Iran 1977 only - Mar 21 23:00 1:00 -
Rule Iran 1977 only - Oct 20 24:00 0 -
Rule Iran 1978 only - Mar 24 24:00 1:00 -
Rule Iran 1978 only - Aug 5 01:00 0 -
Rule Iran 1979 only - May 26 24:00 1:00 -
Rule Iran 1979 only - Sep 18 24:00 0 -
Rule Iran 1980 only - Mar 20 24:00 1:00 -
Rule Iran 1980 only - Sep 22 24:00 0 -
Rule Iran 1991 only - May 2 24:00 1:00 -
Rule Iran 1992 1995 - Mar 21 24:00 1:00 -
Rule Iran 1991 1995 - Sep 21 24:00 0 -
Rule Iran 1996 only - Mar 20 24:00 1:00 -
Rule Iran 1996 only - Sep 20 24:00 0 -
Rule Iran 1997 1999 - Mar 21 24:00 1:00 -
Rule Iran 1997 1999 - Sep 21 24:00 0 -
Rule Iran 2000 only - Mar 20 24:00 1:00 -
Rule Iran 2000 only - Sep 20 24:00 0 -
Rule Iran 2001 2003 - Mar 21 24:00 1:00 -
Rule Iran 2001 2003 - Sep 21 24:00 0 -
Rule Iran 2004 only - Mar 20 24:00 1:00 -
Rule Iran 2004 only - Sep 20 24:00 0 -
Rule Iran 2005 only - Mar 21 24:00 1:00 -
Rule Iran 2005 only - Sep 21 24:00 0 -
Rule Iran 2008 only - Mar 20 24:00 1:00 -
Rule Iran 2008 only - Sep 20 24:00 0 -
Rule Iran 2009 2011 - Mar 21 24:00 1:00 -
Rule Iran 2009 2011 - Sep 21 24:00 0 -
Rule Iran 2012 only - Mar 20 24:00 1:00 -
Rule Iran 2012 only - Sep 20 24:00 0 -
Rule Iran 2013 2015 - Mar 21 24:00 1:00 -
Rule Iran 2013 2015 - Sep 21 24:00 0 -
Rule Iran 2016 only - Mar 20 24:00 1:00 -
Rule Iran 2016 only - Sep 20 24:00 0 -
Rule Iran 2017 2019 - Mar 21 24:00 1:00 -
Rule Iran 2017 2019 - Sep 21 24:00 0 -
Rule Iran 2020 only - Mar 20 24:00 1:00 -
Rule Iran 2020 only - Sep 20 24:00 0 -
Rule Iran 2021 2022 - Mar 21 24:00 1:00 -
Rule Iran 2021 2022 - Sep 21 24:00 0 -
# Zone NAME STDOFF RULES FORMAT [UNTIL]
Zone Asia/Tehran 3:25:44 - LMT 1916
3:25:44 - TMT 1935 Jun 13 # Tehran Mean Time
3:30 Iran +0330/+0430 1977 Oct 20 24:00
4:00 Iran +04/+05 1979
3:30 Iran +0330/+0430
For more information about the config parameters, see the "man zic"
Compile to apply the updates for the Asia/Tehran timeZone through the 'zic' command:
$ zic Tehran_timeZone
Relink the localtime /etc/localtime with the corrected timeZone information using the following command:
# zic -l Asia/Tehran
Note: Depending on what Linux distribution are you using, you will need to reconfigure the ZONE for which system is using at startup (configure with tzdata-update or timedatectl set-timezone Asia/Tehran)
Note: User/shell level timeZone
The date command by default is using the same /etc/localtime when displaying date &time at user/shell level, however if variable TZ was set to something different, then it will read and apply the timeZone from that TZ variable, so you will need to either unset/delete it or set that to the current locatime TZ='Asia/Tehran' in the user level shell profiles; this is a command to find files which TZ variable might set in those files under user's home directories:
# find /home/ -maxdepth 2 -type f -exec grep -wH 'TZ' {} +
Note: You will need to update the same for the system-wide shell profiles.
Part2: Update timeZone for the Java-based applications (OpenJDK, OracleJDK, IBMJDK, etc)
You have an updated timeZone file (https://data.iana.org/time-zones/releases/tzdata2022b.tar.gz)
You need to download a Java-based compiler to compile the tzdata2022b.tar.gz file into Java compatible timezone; we used the open source ZIUpdater tool (Download from https://www.azul.com/products/open-source-tools/ziupdater-time-zone-tool/)
Run below command to compile the timezone from the tzdata2022b.tar.gz package using ziupdater.jar tool:
$JAVA_HOME/bin/java -jar ziupdater.jar -l tzdata2022b.tar.gz
Done. The ziupdater.jar tool will generate tzdb.dat (original location for the tzdb.dat is $JAVA_HOME/lib/tzdb.dat) for JDKv8+ and and for JDKv7 and earlier it will genrate a directory named zi (original location is $JAVA_HOME/lib/zi/*) with all updated timezone files and you only need to replace the old ones with the new ones (you might want to take a backup first from old timezones)
Application restart probably is required.
Notes:
After patching timezone, once you need to:
Unset the TZ environment variable and restart sshd service.
Restart the cron/crond service.
Restart the rsyslog or any other syslog service your server have it running.
Some applications and specifically DBs might not use neither of OS or JDK timeZone files, and for that you need to refer its documentation for how-do-do that separately.
| How to disable DST changes for a timezone? |
1,439,378,149,000 |
I have a tiny script that simply fetches the current date, runs a PHP script and redirect the output (and errors) to a filename containing the current date.
DATE=$(date +"%Y%m%d")
FILE="log/${DATE}.log"
php -q script.php >> $FILE 2>&1
When I run this script on my local machine (Windows 7, Aptana IDE), the PHP script works fine and the logfile has the expected filename, e.g. 20140502.log.
But when I push that script via SFTP to my remote machine and execute that script, the filename looks like this:
20140502?.log?
What might be the problem? Is this an enconding error (e.g. encoding for SFTP uploads is ANSII, where UTF-8 is expected)? Or do I have to change anything in the script itself?
Information about system/shell:
[foo@bar path]$ sh --version
GNU bash, version 3.2.25(1)-release (x86_64-redhat-linux-gnu)
Funny fact: If that script is called by a cronjob, the question marks don't occur. Only if I manually run the script.
|
You probably have some non-printable characters on end of lines (eg. CRLF from Windows), run:
cat -A scriptname
on remote machine, it'll show you all characters in your script.
Then, you can convert to unix-like format running
dos2unix scriptname
| Why does the filename contain question marks when I run a script on my remote machine? |
1,439,378,149,000 |
I am looking for a regular expression that finds all occurences of double characters in a text, a listing, etc. on the command line (Bash).
Main Question: Is there a simple way to look for sequences like aa, ll, ttttt, etc. where one defines a regular expression that looks for n occurences of the same character with? What I am looking for is achieving this on a very very basic level. On the command line. In a Linux Shell.
After quite some research I came to the following answers – and questions resulting from them, thus they just gave me a hint where the solution might be. But:
a) (e)grep and the backslash issue
grep 'a\{2\}' looks for aa
egrep'a{2}' looks for aa
Question: Is the necessity of setting backlashes really bound to the command I use? If so, can anyone give me hint what else is to be taken into account when using (e)grep here?
b) I found this answer here for my question, though it isn't exactly what I was looking for:
grep -E '(.)\1' filename looks for entries with the same character appearing more than once but doesn't ask how often. This is close to what I am looking for, but I still want to set a number of repeatings.
I probably should split this into two or more questions, but then I don't want to flood this awesome site here.
P.S.: Another question, possibly off topic but: is it in, inside, at or on the shell. And is on the command line correct?
|
This really is two questions, and should have been split up. But since the answers are relatively simple, I will put them here. These answers are for GNU grep specifically.
a) egrep is the same as grep -E. Both indicate that "Extended Regular Expressions" should be used instead of grep's default Regular Expressions. grep requires the backslashes for plain Regular Expressions.
From the man page:
Basic vs Extended Regular Expressions
In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \).
See the man page for additional details about historical conventions and portability.
b) Use egrep '(.)\1{N}' and replace N with the number of characters you wish to replace minus one (since the dot matches the first one). So if you want to match a character repeated four times, use egrep '(.)\1{3}'.
| Regular Expression for finding double characters in Bash |
1,439,378,149,000 |
Possible Duplicate:
How can I increase the number of inodes in an ext4 filesystem?
I have a homemade NAS with Debian Wheezy 64bit. It has three disks - 2x2TB and 1.5TB, pooled together using RAID1/5 and LVM. The result is a LVM Logical Volume, about 3.16TB in size, formatted as ext4 and mounted as /home. However I just found out that roughly 50GB of this capacity is used by Inodes (exact count being 212 459 520, with 256B in size or to put it in another way - one Inode per every 16k of the partition size).
While 50GB in 3.16TB is about 1.5% of the total capacity, it's still a lot of space. Since this is a storage NAS, mostly used for multimedia, I don't ever expect the /home partition to have 212 million files in it.
So, my question is this - is it possible to lower/change the number of Inodes without actually re-creating the whole partition? While it might be possible to do it, I'd still prefer to find a way to do so instead of moving 2TB of data around and waiting for RAID to re-sync again.
|
From the mke2fs man page:
Be warned that it is not possible to expand the number of inodes on a filesystem after it is created, so be careful deciding the correct value for this parameter.
So the answer is no.
What you could do is shrink the existing ext4 volume (this requires unmounting the filesystem), use the free space to create a new ext4 volume with fewer inodes, copy the data, remove the old volume and extend the new volume to occupy all the space.
| Is it possible to change Inode count on an ext4 filesystem? [duplicate] |
1,439,378,149,000 |
I have 2x2 GiB sticks of RAM installed.
Running memtest86 from the grub boot menu confirms this.. memtest86 reports no errors.
However every which way I check my available memory in a running Ubuntu 10.04 system, it reports only approximately 3.2 GiB.
cat /proc/meminfo == 3320132 kB
System Monitor == 3.2 GiB
htop == 3242 MB
free -m == 3242 MB
Who's got my missing RAM ?
Updated info: I just now dual-booted into another version of Ubuntu 10.04 on the same hardware (I forgot I had installed it many months ago, for emergencies) :).... It reports 3.9 GiB, via System Monitor...
I've posted my most recent /var/log/messages information at http://pastebin.ubuntu.com/629246/
|
A 32-bit address space means that you have space for 4GB of addresses. Ideally the kernel likes to be able to map all physical memory, all the memory of the current task, and all of its own memory. If physical memory alone takes up all of the available 4GB, that won't work. So physical memory is divided into low memory, which is mapped all the time, and high memory, which must be mapped when in use. Unless you're running a patched kernel, on the ix86 architecture, 128MB of address space is devoted to kernel code and data structures, and 896MB is devoted to mapping physical memory (for a total of 1GB).
Background reading on the complexities of memory management when your address space isn't comfortably larger than your total memory:
High memory on the Linux memory manager wiki
High memory in the Linux kernel on Kernel Trap
Memory mapping chapter in LDD3
Excerpts from your kernel logs:
BIOS-provided physical RAM map:
BIOS-e820: 0000000000000000 - 000000000009f800 (usable)
BIOS-e820: 000000000009f800 - 00000000000a0000 (reserved)
BIOS-e820: 00000000000f0000 - 0000000000100000 (reserved)
BIOS-e820: 0000000000100000 - 00000000cdce0000 (usable)
BIOS-e820: 00000000cdce0000 - 00000000cdce3000 (ACPI NVS)
BIOS-e820: 00000000cdce3000 - 00000000cdcf0000 (ACPI data)
BIOS-e820: 00000000cdcf0000 - 00000000cdd00000 (reserved)
BIOS-e820: 00000000d0000000 - 00000000e0000000 (reserved)
BIOS-e820: 00000000fec00000 - 0000000100000000 (reserved)
BIOS-e820: 0000000100000000 - 0000000130000000 (usable)
2404MB HIGHMEM available.
887MB LOWMEM available.
Zone PFN ranges:
DMA 0x00000000 -> 0x00001000
Normal 0x00001000 -> 0x000377fe
HighMem 0x000377fe -> 0x000cdce0
Here you have 887MB of low memory: the theoretical maximum of 896MB minus a few MB of DMA buffers (zones of memory used to communicate with hardware devices).
Of your physical memory, 3328MB is mapped at addresses below 4GB and 768MB is mapped at addresses above 4GB (the 0x100000000–0x130000000 range). You're not getting access to these 768MB, which explains why you only have 3242MB available (4096MB of RAM minus 768MB inaccessible minus 9MB of DMA buffers minus 75MB used by the kernel itself for code and data). I don't know why the BIOS maps some RAM above the 4GB mark, but as a data point, I'm posting this from a PC with 4GB of RAM that similarly has RAM mapped at 0x100000000–0x130000000.
Mapping physical memory above 4GB requires using PAE. PAE incurs a small performance overhead (in particular, it requires bigger data structures in the memory manager), so it's not systematically enabled. The default Ubuntu kernel is compiled without PAE support. Get the -generic-pae kernel to be able to access up to 64GB of RAM.
TL,DR: Linux is working as expected. The firmware isn't so helpful. Get a PAE-enabled kernel.
| Why does my system show only 3.2 GiB of RAM when I definitely have 4.0 GiB |
1,439,378,149,000 |
I have some devices connected to a Cisco serial term server; many work fine when I telnet directly to the port on the Cisco. However, I have a few stubborn devices that will not use Backspace as it is mapped in telnet by default.
In case it matters, I telnet from rxvt under Debian squeeze (in an X Window). TERM is set to rxvt, but it doesn't matter whether I use vt100, vt101, or xterm... changing TERM has no effect. I started down the road of changing TERM based on what I saw in an old Kermit FAQ. FWIW, stty erase ^h and stty erase ^? don't work either.
I have noticed that Backspace works correctly on these devices if I use a raw TCP socket from netcat... i.e. nc 192.168.12.117 2006; however, then I run into other issues with passwords not hidden or terminal paging.
How can I selectively force telnet and ssh to map Backspace to CtrlH for these devices? Also, what criteria should I use to evaluate whether this is a bug in the device?
EDIT
In case it matters, this is the output from showkey -a for the keys in question... ^? corresponds to Backspace and ^H is CtrlH. It seems like I should be getting close when I look at The Linux Keyboard and Console Howto, but I can't seem to decipher what I can do to change this. I have tried various incantations with loadkeys to no effect.
[mpenning@hotcoffee docs]$ sudo showkey -a
Press any keys - Ctrl-D will terminate this program
^? 127 0177 0x7f
^H 8 0010 0x08
I am also including relevant output from dumpkeys as well... this is the current mapping in my system (which doesn't work on some devices in question). If I could figure out how to get Backspace to do the same thing as CtrlH, I would have a solution.
[mpenning@hotcoffee docs]$ sudo dumpkeys | grep -Ei "backspace|127"
keycode 8 = BackSpace ampersand braceleft
keycode 14 = BackSpace Delete
control keycode 14 = BackSpace
keycode 127 =
[mpenning@hotcoffee docs]$
|
I finally found an answer in Anne Baretta's Linux Keyboard Hall of Shame... it seems that changing key mappings in xterm / rxvt does no good for telnet.
I validated this when I sniffed the telnet connection. First I sniffed the telnet session and saw that Backspace sent 0x7f to the host. Next I intentionally broke Backspace in rxvt using stty erase $ (thus mapping my Backspace to the dollar sign in rxvt). After doing this, I had to hit $ to backspace in rxvt, but telnet still sent 0x7f when I used Backspace on the remote host.
SOLUTION
Create a script called kbdfix (below), and make it executable with 755 permissions; you will need the tclsh and expect packages loaded from your distribution archives.
#!/usr/bin/expect
#Name this file as kbdfix and make it executable in your path
eval spawn -noecho $argv
interact {
\177 {send "\010"}
"\033\[3~" {send "\177"}
}
Now to connect to the broken hosts, I type kbdfix telnet 192.168.12.117 2006, and Backspace works.
Note for anyone confused by 2006 above... that is the TCP port that the Cisco term server uses for the serial connection to the console of the broken device (in this case, a Brocade FCX switch).
If you are merely telnetting to a device that doesn't like Backspace, you would use kbdfix telnet <addr_of_the_broken_device>. I am also using this with ssh when I ssh to a DLink DGS-3200 Ethernet switch that has similar issues; the syntax is kbdfix ssh 172.16.1.26.
| Force telnet / ssh to use crtl-H for backspace |
1,439,378,149,000 |
I have got a bit lost and am not sure which technology to choose for full disk encryption. It is hard to tell if the information out there is still up to date. Is there a current best practice solution for this?
|
There are basicly 2 'standard' tools for partions:
TrueCrypt - cross-platform, open, plausible deniability
dm-crypt - Linux-specific, uses Linux Crypto API, can take advantages of any crypto hardware acceleration Linux supports, and device-mapper.
There's also cryptoloop, dm-crypt's predecessor
| Best way to do full disk encryption? |
1,439,378,149,000 |
I am now installing a new Linux server with CentOS-7. Before, I used CentOS-6 on all machines and used uid = 555 for my account. However, on CentOS-7, it seems that uid <= 999 are reserved for system (accoding to some articles on the net). For testing purpose, I have tried to make an account with uid = 555, such that
# useradd -u 555 {my-login-name}
Then, a new account was created even on CentOS-7 with no warning etc from the command.
I understand that uid <= 999 is "reserved for system", but practically speaking, is there any serious problem to keep using the above uid (555)? Or, considering the future possibility that a new service may use 555, should I avoid using it? I appreciate any advice for this!
EDIT
The /etc/login.defs on my new machine (Centos-7) shows
# Min/max values for automatic uid selection in useradd
#
UID_MIN 1000
UID_MAX 60000
while that on my old machine (Centos-6) is
# Min/max values for automatic uid selection in useradd
#
UID_MIN 500
UID_MAX 60000
so having different UID_MIN. Also, /etc/passwd on my new machine looks like
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
pegasus:x:66:65:tog-pegasus OpenPegasus WBEM/CIM services:/var/lib/Pegasus:/sbin/nologin
ods:x:999:998:softhsm private keys owner:/var/lib/softhsm:/sbin/nologin
systemd-bus-proxy:x:998:996:systemd Bus Proxy:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
polkitd:x:997:995:User for polkitd:/:/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
colord:x:996:993:User for colord:/var/lib/colord:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
unbound:x:995:992:Unbound DNS resolver:/etc/unbound:/sbin/nologin
usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin
libstoragemgmt:x:994:991:daemon account for libstoragemgmt:/var/run/lsm:/sbin/nologin
saslauth:x:993:76:Saslauthd user:/run/saslauthd:/sbin/nologin
dirsrv:x:389:389:389-ds-base:/usr/share/dirsrv:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
amandabackup:x:33:6:Amanda user:/var/lib/amanda:/bin/bash
pcp:x:388:388:Performance Co-Pilot:/var/lib/pcp:/sbin/nologin
geoclue:x:387:386:User for geoclue:/var/lib/geoclue:/sbin/nologin
setroubleshoot:x:386:385::/var/lib/setroubleshoot:/sbin/nologin
postfix:x:89:89::/var/spool/postfix:/sbin/nologin
memcached:x:385:384:Memcached daemon:/run/memcached:/sbin/nologin
rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin
mysql:x:27:27:MariaDB Server:/var/lib/mysql:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
chrony:x:384:383::/var/lib/chrony:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
sssd:x:383:382:User for sssd:/:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
pulse:x:171:171:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
hsqldb:x:96:96::/var/lib/hsqldb:/sbin/nologin
tomcat:x:91:91:Apache Tomcat:/usr/share/tomcat:/sbin/nologin
pkiuser:x:17:17:Certificate System:/usr/share/pki:/sbin/nologin
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
gnome-initial-setup:x:382:379::/run/gnome-initial-setup/:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
oprofile:x:16:16:Special user account to be used by OProfile:/var/lib/oprofile:/sbin/nologin
From the uid shown above, it seems to me that new services use uid from 999(ods) -> 998 (systemd-bus-proxy) -> 997(polkitd) -> ... -> 993(saslauth). So, if this scheme is followed by other new services as well (in future), there may be little risk for using 555 (for me). FYI, other users (except me) already have uid >= 1000, so no problem for them. But I've been using 555 for other machines (including Mac), so still wondering if it's better to use uid >= 1000 from now on.
|
Well, i'm glad you ask, because it's an interesting question.
As per Wikipedia:
The Linux Standard Base Core Specification specifies that UID values
in the range 0 to 99 should be statically allocated by the system, and
shall not be created by applications, while UIDs from 100 to 499
should be reserved for dynamic allocation by system administrators and
post install scripts.[4]
On FreeBSD, porters who need a UID for their package can pick a free
one from the range 50 to 999 and then register the static
allocation.[5][6]
Some POSIX systems allocate UIDs for new users starting from 500 (OS
X, Red Hat Enterprise Linux), others start at 1000 (openSUSE,
Debian[7]). On many Linux systems, these ranges are specified in
/etc/login.defs, for useradd and similar tools.
Central UID allocations in enterprise networks (e.g., via LDAP and NFS
servers) may limit themselves to using only UID numbers well above
1000, to avoid potential conflicts with UIDs locally allocated on
client computers. NFSv4 can help avoid numeric identifier collisions,
by identifying users (and groups) in protocol packets using
"user@domain" names rather than integer numbers, at the expense of
additional translation steps.
Source: https://en.wikipedia.org/wiki/User_identifier
So what i get from this is:
- Less than 50 to 99 == high risks of conflicts with system applications
- Less than 499 = risk of conflicts with programs
- Less than 1000 = small risk of conflicts with programs
- For network UID systems, you want to use only high numbers
In the worst case, still from my understanding, you might have a program or user or group, that is allowed to interact with files or process from other programs... I guess it's not a big deal on most small servers, but might become an important security breach on bigger systems.
| user ID less than 1000 on CentOS 7 |
1,439,378,149,000 |
I'm trying to compile a C program and it tells me
user@cu-cs-vm:~/Downloads/pa5$ make
gcc -c -g -Wall -Wextra `pkg-config fuse --cflags` fusehello.c
Package fuse was not found in the pkg-config search path.
Perhaps you should add the directory containing `fuse.pc'
to the PKG_CONFIG_PATH environment variable
No package 'fuse' found
fusehello.c:21:18: fatal error: fuse.h: No such file or directory
compilation terminated.
When I try to install fuse, it just tells me it's already installed.
sudo apt-get install fuse
I looked in usr/lib/pkgconfig and fuse.pc wasn't there. Should it be there?
|
I don't know which distro you are using, but you probably need to install libfuse-dev. The fuse header files are missing.
| fuse is installed but compiler is saying "no package 'fuse' found |
1,439,378,149,000 |
I want to know what the easiest way is to determine (without root privilege) whether a block device (say sdb) or any part of it is mounted (and which part of it).
Checking /proc/mounts for sdb is not enough because sdb or one of its partitions may be used by LVM. You can check /sys/block/sdb/sdb*/holders/ but you get dm-x entries which have to be resolved to /dev/mapper names in order to check /proc/mounts. Possible but if there is an easier solution... (which should not require root privilege)
|
This is essentially a matter of checking a whole bag of corner cases.
A drive can appear in /proc/mounts
A drive can be used as swap (use /proc/swaps)
A drive can be part of an active LVM pv (use pvdisplay)
A drive can be part of a dm-mapper RAID group (use /proc/mdstat)
A drive can be directly accessed by an application (e.g. Oracle supports writing directly to a drive or partition instead of a filesystem) (use fuser)
A drive can be directly accessed by a virtual machine (use fuser)
A drive can be referenced by a loopback device (e.g: mount /dev/sda -o offset=1M /foo) (use losetup -a)
These are just the examples I came up with given a minute and a half to think about it. I'm sure there's a dozen others.
This last example I think is the most interesting and few people know about it. It allows you to mount a filesystem without using partitions. Just specify the starting offset and Linux will transparently create a loopback device. The example above yields the following:
# cat /proc/mounts
...
/dev/loop0 /foo ext4 relatime,data=ordered 0 0
# losetup -a
/dev/loop0 [0005]:2048 (/dev/sda), offset 1048576
Why would you do that? Typically it involves situations where things have previously gone horribly wrong.
Also bear in mind that with the namespacing feature now in mainline (see unshare), different processes can have different views about what's mounted and what isn't. Here things start to get a little bit red-pill.
| How to find out easily whether a block device (or a part of it) is mounted somehow |
1,439,378,149,000 |
I have a Linux kernel module which I compiled dynamically. How is it added to startup? There are lot of .ko files in /lib/modules. How is priority set for loading these modules?
|
They are not loaded automatically at start-up or any other time, although a lot of them do end up being loaded during boot. There are three different mechanisms by which this happens:
Userspace request: Which covers everything from init services to udev to the command-line. Init or udev are probably the most straightforward means if you want to load a specific module at boot time.
Hotplugged device: When you connect something to, e.g., USB or PCI, the kernel detects this and requests an appropriate module based on how the device identifies itself.
Needed protocol or other implementation: When the kernel needs to do something, such as read a filesystem, and discovers it lacks the knowledge to do so, it will request a module.
Notice that for the last two I used the phrase "request a module" -- this is because the kernel actually loads via a userspace daemon, kmod which executes /sbin/modprobe. According to Wolfgang Mauerer in Linux Kernel Architecture, there are only ~100 different points in the 2.6 kernel where it calls an internal request_module() function.
modprobe uses a database of installed MODULE_ALIAS's. These are specified in the module source code explicitly, or derived from it's MODULE_DEVICE_TABLE, which is a list of OEM device IDs that the module services.
| What is the sequence loading linux kernel module on startup? How priority is set to them? |
1,439,378,149,000 |
When I use KVM, I create a virtual bridge called virbr0, there is also a bridge called virbr0-nic. Even after I disable and delete virbr0, the virbr0-nic is still there.
Can anyone explain to me what is this?
Thank you.
|
The interface virbr0-nic is not a bridge, but a normal ethernet interface (although a virtual one, created with ip add type veth).
It's there so that the bridge has at least one interface beneath it to steal it's mac address from. It passes no real traffic, since it's not really connected to any physical device.
The bridge would work without it, but then it could change it's mac address as interfaces enter and exit the bridge, and when the mac of the bridge changes, external switches may be confused, making the host lose network for some time.
| What is virtual bridge with -nic in the end of name |
1,439,378,149,000 |
Most Linux distributions ship with a certain kernel version and only update it on point releases (x.y.z to x.y.(z+1)) and for security updates.
On the other hand, I know that Linux has a very strict policy about not changing the kernel ABI and never breaking user space. In fact, Linus have had many public tantrums directed at developers who wanted to (intentionally or accidentally) change the kernel is non-backwards-compatible ways.
I don't understand why distributions use "stable" kernels instead of always updating to the latest kernel. This is not a criticism, I'm just curious about the reason.
|
The Linux kernel's system call interfaces are very stable. But the kernel has other interfaces that aren't always compatible.
/proc is mostly stable, but there have been a few changes in the past (e.g. some interfaces moving to /sys some time after /sys was created).
A number of device-related interfaces have been removed in the past.
/sys contains some stable interfaces (listed in Documentation/ABI/stable) and some that aren't. You aren't supposed to use the ones that aren't, but sometimes people do, and a simple security and stability upgrade shouldn't break things for them.
There have been incompatibilities with modutils in the past (newer kernels requiring a newer version of modutils), though I think it was quite a while ago.
There have also been incompatibilities with respect to the boot process on some unusual configurations. Even increasing the size of the kernel could cause problems on some embedded systems.
While the kernel's external interfaces are pretty stable, the internal interfaces are not. The rule for internal interfaces is that anyone can break them as long as they fix internal uses, but fixing third-party modules is the responsibility of the author of said modules. Overall quite a lot of installations run third-party modules: extra drivers for hardware that wasn't supported by the kernel (if the hardware is supported by the new kernel, that's fine, but what if it isn't), proprietary drivers (while the world would be a better place if all drivers were open source, this isn't the case; for example, if you want good 3D GPU performance, you're pretty much stuck with proprietary drivers), etc.
Some people need to recompile their kernel, or some third-party modules. More recent kernels often can't be compiled with older compilers.
All in all, the primary reason not to switch to a more recent kernel version is third-party modules.
Some distributions nonetheless offer recent kernels as an option. For example, Debian makes kernels from testing available to users of the stable release through backports. Similarly, on Ubuntu LTS, kernels from more recent Ubuntu releases are available, but not used by default. This is mostly useful for new installations on hardware that wasn't supported yet when the distribution was finalized.
| What prevents distributions from using the latest Linux kernel? [closed] |
1,439,378,149,000 |
What file in Ubuntu is equivalent to the /etc/inittab file in RedHat?
In RedHat the /etc/inittab file contains the settings related to the runlevel in which you want to boot Linux.
|
Ubuntu uses Upstart, an alternative to sysvinit, which works completely differently. The Upstart CookBook discusses runlevels and how to work with them.
Generally, though, the RedHat concept of runlevels isn't used on Debian or derivatives, including Ubuntu; they have only "single user" or "everything running", without any of the "network, but not graphics" style distinctions that RedHat draws.
| File in Ubuntu equivalent to /etc/inittab file in RedHat |
1,439,378,149,000 |
on one of the boxes I don't control at work I use ssh keys to log in. Our passwords are set to expire after a few months. What happens if I don't reset my password and it expires? will I still be able to login? Does what happens depend on some sshd setting? or some pam setting?
|
Under default behavior, you will still be able to log in using your ssh key, but the system administrator is free to change this behavior using pam or other methods. OpenSSH doesn't care about the expiration date on your password if it's not using password authentication, but pam can be set up to check password expiration even after sshd has authenticated your key. It could probably even be set up to force you to enter and change your expired password before handing you the shell prompt. For the best answer, ask your sysadmin.
EDIT: For more details on the interaction between SSH and PAM, see this answer.
| What happens when your password expires and you're using key authentication? |
1,439,378,149,000 |
I'm migrating some software from Unix to Linux.
I have the following script; it is a trigger of a file transfer.
What do the exec commands do?
Will they work also on Linux?
#!/bin/bash
flog=/mypath/log/mylog_$8.log
pid=$$
flog_otherlog=/mypath/log/started_script_${8}_${pid}.log
exec 6>&1
exec 7>&2
exec >> $flog
exec 2>&1
exec 1>&6
exec 2>&7
/usr/local/bin/sudo su - auser -c "/mypath/bin/started_script.sh $1 $pid $flog_otherlog $8"
The started script is the following:
#!/bin/bash
flusso=$1
pidpadre=$2
flogcurr=$3
corrid=$4
pid=$$
exec >> $flogcurr
exec 2>&1
if [ $1 = pippo ] || [ $1 = pluto ] || [ $1 = paperino ]
then
fullfile=${myetlittin}/$flusso
filename="${flusso%.*}"
datafile=$(ls -le $fullfile | awk '{print $6, " ", $7, " ", $9, " ", $8 }')
dimfile=$(ls -le $fullfile | awk '{print $5 " " }')
aaaammgg=$(ls -E $fullfile | awk '{print $6}'| sed 's#-##g')
aaaamm=$(echo $aaaammgg | cut -c1-6)
dest_dir=${myetlwarehouse}/mypath/${aaaamm}
dest_name=${dest_dir}/${filename}_${aaaammgg}.CSV
mkdir -p $dest_dir
cp $fullfile $dest_name
rc_copia=$?
fi
I will change ls -le into ls -l --time-style="+%b %d %T %Y" and ls -E into ls -l --time-style=full-isoand in Linux.
|
exec [n]<&word will duplicate an input file descriptor in bash.
exec [n]>&word will duplicate an output file descriptor in bash.
See 3.6.8 in: https://www.gnu.org/software/bash/manual/html_node/Redirections.html
The order of arguments can be confusing, though.
In your script:
exec 6>&1 creates a copy of file descriptor 1, i.e. STDOUT, and stores it as file descriptor 6.
exec 1>&6 copies 6 back unto 1.
It could also have been moved by appending a dash, i.e. 1<&6- closing descriptor 6 and leaving only 1.
In between, you'll usually find operations that write to STDOUT and STDIN, e.g. in a subshell.
Also see: Practical use for moving file descriptors
| What does `exec 6>&1` or similar do? |
1,439,378,149,000 |
If we create a swapfile with fallocate we are told that the file contains holes and therefore the operation is halted.
What are these holes?
Is it unallocated disk space, which makes the whole file allocation a hole itself?
Like this:
block1 -> empty
block2 -> empty
block3 -> empty
or
is it the blocks preallocated contains holes in between, and
therefore they are not contiguous? Like this:
block1
block2
hole in block3 [occupied by other file in the disk]
block4
Test
fallocate -l 100MB /swap
chmod 600 /swap
mkswap /swap
swapon /swap
Output
swapon: swapfile has holes
swapon: /swap: swapon failed: Invalid argument
|
Holes in a file don’t have any block associated with them at all. A file created with fallocate can end up with no blocks associated with it, only a size. Reads from unallocated blocks always return all zeroes; writes to an unallocated block cause the file system to allocate a block (filling the hole, at least partially) before writing.
Files with holes can’t be used for swap because the kernel expects to be able to access the file’s blocks without help from the file system (once the list of blocks is determined). Any file which isn’t fully allocated (containing holes, or copy-on-write) can’t be used for swap because some writes will involve the file system.
You can see how many blocks are really used by a file with stat:
$ truncate -s 16K holes
$ stat holes
File: holes
Size: 16384 Blocks: 0 IO Block: 4096 regular file
Device: fd13h/64787d Inode: 36708573 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ steve) Gid: ( 1000/ steve)
Access: 2019-05-12 20:04:22.498258356 +0200
Modify: 2019-05-12 20:04:22.498258356 +0200
Change: 2019-05-12 20:04:22.498258356 +0200
Birth: -
filefrag will tell you what’s allocated:
$ /usr/sbin/filefrag holes
holes: 0 extents found
Forcing partial allocation of the file will reduce the hole:
$ fallocate -z -l 8K holes
$ stat holes
File: holes
Size: 16384 Blocks: 16 IO Block: 4096 regular file
Device: fd13h/64787d Inode: 36708573 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 1000/ steve) Gid: ( 1000/ steve)
Access: 2019-05-12 20:04:22.498258356 +0200
Modify: 2019-05-12 20:10:12.520380272 +0200
Change: 2019-05-12 20:10:12.520380272 +0200
Birth: -
$ /usr/sbin/filefrag -e holes
Filesystem type is: ef53
File size of holes is 16384 (4 blocks of 4096 bytes)
ext: logical_offset: physical_offset: length: expected: flags:
0: 0.. 1: 116741448.. 116741449: 2: last,unwritten
holes: 1 extent found
| What are the holes in files created with fallocate? |
1,439,378,149,000 |
I have a partition sdb1 of size 3.3 GB. From 3.3 GB only 1.9 GB is used and 1.2 GB is an empty space. I want to create an image of this partition.
But I want the image to only have the used space i.e. 1.9 GB
Now when I run a command using dd:
dd if=/dev/sdb1 of=/home/data/Os.img bs=1M status=progress
I saw behavior that dd is making the image of 3.3 GB While I don't want the unallocated space to be the part of the OS image.
So I tried different solutions. I found one solution:
dd if=/dev/sdb1 of=/home/data/OS.img bs=1M count=1946 status=progress
This solution created an image of 1.9 GB as I have defined a block size of 1M and count is 1946 which will give 1.9 GB totally.
Question
I am unable to determine if this dd command only made an image of the used space or it just created an image of size 1.9 GB in which there are both used and unused spaces?
And is there any other way in which the image can be created for the used space only?
|
This has been answered here.
First make an image of the partition.
Then use losetup to mount the image. As it's not a disk but a partition, you don't need the partscan flag.
# lsblk
# losetup --find foo.img
Lookup the newly created loop device
# lsblk
loop1 7:1 0 4096M 0 loop
Zero out the remaining space by writing a large empty file.
# mount /dev/loop1 /mnt
# dd if=/dev/zero of=/mnt/filler conv=fsync bs=1M
# rm /mnt/filler
# umount /dev/loop1
Now compress the image.
# ls -s
4096M foo.img
# gzip foo.img
# ls -s
11M foo.img.gz
So far for the partition image.
If there is an ext4 file system on the partition, you can resize it with resize2fs to the minimum size. This moves all data to the first blocks.
e2fsck -f /dev/loop1
resize2fs -M /dev/loop1
| Create an image of the partition (only the used space) |
1,439,378,149,000 |
I simply open an http server from my terminal (with node) listening on port 3000, which is obviously working if I request localhost:3000 in a browser.
Now, I want to see this connection so I use netstat.
I'm supposed to see server connection on port 3000, and client connection on another port:
$ netstat -p tcp
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp6 0 0 localhost.hbci localhost.50215 ESTABLISHED
tcp6 0 0 localhost.50215 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50214 ESTABLISHED
tcp6 0 0 localhost.50214 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50213 ESTABLISHED
tcp6 0 0 localhost.50213 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50211 ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50212 ESTABLISHED
tcp6 0 0 localhost.50212 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.50211 localhost.hbci ESTABLISHED
tcp6 0 0 localhost.hbci localhost.50210 ESTABLISHED
tcp6 0 0 localhost.50210 localhost.hbci ESTABLISHED
No entries about the server connection on port 3000. But the localhost.hbci, switching from a local to a foreign address, seems to be my server connection.
And if I type:
$ lsof -i TCP:3000
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 1144 garysounigo 11u IPv6 0x6d9a12e1e288efc7 0t0 TCP *:hbci (LISTEN)
I'm sure that hbci represent my port 3000.
Does anyone know something about what hbci means or refers to?
Is it a port for local server ? A protocol for s local connection?
I find anythings everywhere ( on any port.. ;) )
|
Does anyone know what hbci means or refers to?
HBCI stands for "Home Banking Computer Interface", see http://openhbci.sourceforge.net/. The same port number is also used by the "RemoteWare Client", at least according to http://www.networksorcery.com/enp/protocol/ip/ports03000.htm.
The reason you are seeing it is because netstat and similar utilities look up port numbers in a database that maps them to symbolic names (usually, /etc/services).
To suppress this behavior in netstat, one can pass the --numeric-ports option, or just -n which also makes some other things numeric.
| TCP *:hbci (LISTEN) - What does hbci mean? [duplicate] |
1,439,378,149,000 |
On Linux, I want to know which process uses my disk I/O bandwith.
I know I can use iotop but I have a machine where, for various reasons, iotop cannot be installed.
How can I manually get that information? (How does iotop itself proceed?)
|
The file in /proc/<pid>/io represent what you need. It's a bit scripting work to get an output similar to iotop. See the linux kernel documentation to the /proc/<pid>/io file values:
rchar
I/O counter: chars read The number of bytes which this task has caused
to be read from storage. This is simply the sum of bytes which this
process passed to read() and pread(). It includes things like tty IO
and it is unaffected by whether or not actual physical disk IO was
required (the read might have been satisfied from pagecache)
wchar
I/O counter: chars written The number of bytes which this task has
caused, or shall cause to be written to disk. Similar caveats apply
here as with rchar.
[...]
read_bytes
I/O counter: bytes read Attempt to count the number of bytes which
this process really did cause to be fetched from the storage layer.
Done at the submit_bio() level, so it is accurate for block-backed
filesystems.
write_bytes
I/O counter: bytes written Attempt to count the number of bytes which
this process caused to be sent to the storage layer. This is done at
page-dirtying time.
Now, you can use that small bash script:
#!/bin/bash
if [ "$(id -u)" -ne 0 ] ; then
echo "Must be root" 2>&1
exit 1
fi
delay=2
lista=$(for p in $(pgrep "."); do echo -n "$p "; grep ^rchar /proc/$p/io 2>/dev/null; done)
while :; do
echo "-----"
listb=$(for p in $(pgrep "."); do echo -n "$p "; grep ^rchar /proc/$p/io 2>/dev/null; done)
echo "$lista" | while read -r pida xa bytesa; do
[ -e "/proc/$pida" ] || continue
echo -en "$pida:\t"
bytesb=$(echo "$listb" | awk -v pid=$pida '$1==pid{print $3}')
echo "$((($bytesb - $bytesa) / $delay)) b/s"
done | sort -nk2 | tail
sleep $delay
listb=$lista
done
It creates two lists with a delay of 2 seconds ($delay: can be in- or decreased) between them, and then compares the lists and calculates the differences. The 10 process with the most I/O are printed with their I/O bandwith in the last 2 seconds. If you want write I/O instead of read I/O just edit the grep command in the lists to wchar instead of rchar:
lista=$(for p in $(pgrep "."); do echo -n "$p "; grep ^wchar /proc/$p/io 2>/dev/null; done)
listb=$(for p in $(pgrep "."); do echo -n "$p "; grep ^wchar /proc/$p/io 2>/dev/null; done)
| Know which process does I/O without iotop |
1,394,071,337,000 |
All the questions I've seen refer to running a 32-bit app in a 64-bit system.
I'm running 32-bit Ubuntu 12.04 (actually elementary OS Luna, which is based on it) and I'm trying to run a 64-bit app which refuses open. Running:
./64bit_app.run
(where 64bit_app.run is the 64-bit app I'm trying to run) results in:
bash: ./64bit_app.run: no se puede ejecutar el fichero binario
which translates to "can't execute/run/open binary file".
Should I be able to run it? Is it possible to run a 64-bit app in a 32-bit system? If so, how?
|
You can't do that directly on Linux on x86_64 with a 32bit kernel. You need a 64bit kernel to be able to run 64bit code. (Note: kernel. You can have 32bit userland running on a 64bit kernel, and install support for 64bit binaries. How easy this is depends on the distribution. Example here for Debian.)
Some virtualization software is able to do that (with restrictions on the type of CPU you're using), and emulators can do that too. But to run it natively you'll need a 64bit kernel.
Since most 64bit distributions out there have 32bit support (either by default or installable), that's what you should be using if you need to run both 64bit and 32bit binaries on the same OS.
| Run 64-bit app on 32-bit Ubuntu system |
1,394,071,337,000 |
When I plug in my no-name USB 2.0 hub
with a mouse and a keyboard connected to it,
that USB port on my computer stops working:
Devices connected to it,
whether through a hub or directly,
are not detected anymore.
A restart of the system makes the port work again,
but I'd rather have a more gentle method,
which only "resets" the USB controllers.
|
I wrote a script that works for me (on Debian 11):
#!/usr/bin/env bash
# Resets all USB host controllers of the system.
# This is useful in case one stopped working
# due to a faulty device having been connected to it.
base="/sys/bus/pci/drivers"
sleep_secs="1"
# This might find a sub-set of these:
# * 'ohci_hcd' - USB 3.0
# * 'ehci-pci' - USB 2.0
# * 'xhci_hcd' - USB 3.0
echo "Looking for USB standards ..."
for usb_std in "$base/"?hci[-_]?c*
do
echo "* USB standard '$usb_std' ..."
for dev_path in "$usb_std/"*:*
do
dev="$(basename "$dev_path")"
echo " - Resetting device '$dev' ..."
printf '%s' "$dev" | sudo tee "$usb_std/unbind" > /dev/null
sleep "$sleep_secs"
printf '%s' "$dev" | sudo tee "$usb_std/bind" > /dev/null
echo " done."
done
echo " done."
done
echo "done."
NOTE:
It requires root access to reset the controllers.
Idea taken from:
https://www.linux.org/threads/resetting-the-usb-subsystem.10404/
| How to reset USB controllers? |
1,394,071,337,000 |
I have found information that /proc/sys/kernel/random/entropy_avail indicates number of bits available in /dev/random. I wanted to check whether the next reading from /dev/random will block and my naive approach was just to compare entropy_avail and number of required random bits but it does not work well. When I did a simple stupid experiment I realized that the entropy is buffered. 64-bit entropy buffer provides 6 bytes of random data.
I monitored the entropy_avail via this simple command:
while true; do
cat /proc/sys/kernel/random/entropy_avail
sleep 1
done
And I was trying to get a random byte via command
dd if=/dev/random bs=1 count=1 > /dev/null
The dd command is blocked if entropy is 63 or lower. When entropy reaches 64 and I read a byte then entropy decreases to 0 but I can read another 5 bytes without blocking. Then dd blocks again till entropy reaches 64.
What is the exact meaning of the entropy_avail and how can I detect real number of available random bits?
|
entropy_avail does not indicate the number of bits available in /dev/random. It indicates the kernel's entropy estimate in the RNG state that powers /dev/random. That entropy estimate is a pretty meaningless quantity, mathematically speaking; but Linux blocks /dev/random if the entropy estimate is too low.
A program reading from /dev/random blocks until the value in /proc/sys/kernel/random/entropy_avail becomes larger than /proc/sys/kernel/random/read_wakeup_threshold. Reading from /dev/random consumes entropy at the rate of 8 bits per byte.
But anyway you shouldn't be using /dev/random. You should be using /dev/urandom, which is just as secure, including for generating cryptographic keys, and which doesn't block. Generating random numbers does not consume entropy: once the system has enough entropy, it's good for the lifetime of the universe. The OS saves an RNG seed to a file, so once the system has had enough entropy once, it has enough entropy even after a reboot.
The only cases where /dev/urandom is not safe are on a freshly-installed system booting for the first time, on a live system which has just booted (so generating cryptographic keys from a live system is not a good idea!), or on a freshly-booted embedded device that doesn't have either a hardware RNG or persistent memory. On such systems, wait until /dev/random agrees to let out 16 bytes to make sure the entropy pool is built up. Then use /dev/urandom.
| How to check if reading from /dev/random will block |
1,394,071,337,000 |
On Windows one can enforce pressing Ctrl+Alt+Del to fire an interrupt that brings up the login window.
When logging onto a console of a Linux computer: How can I tell if this login is a real one or a mocked up on to steal my credentials?
|
Assuming that you want to be protected against other normal users of the
system (if the adversary has root access, all bets are off), your
could in principle use a secure attention
key:
An operating system's Secure Attention Key is a security tool which is
provided as protection against trojan password capturing programs. It
is an undefeatable way of killing all programs which could be
masquerading as login applications. Users need to be taught to enter
this key sequence before they log in to the system.
(Linux 2.4.2 Secure Attention Key (SAK) handling, Andrew Morton, 18 March 2001)
This related U&L question may be of interest: How can I find the Secure Attention Key (SAK) on my system and can I disable it?
| How to tell if console login is genuine? |
1,394,071,337,000 |
I found the output of dmesg and content of /var/log/dmesg are different. Then what differences are between their purposes?
|
The dmesg command shows the current content of the kernel syslog ring buffer messages while the /var/log/dmesg file contains what was in that ring buffer when the boot process last completed.
| Difference between output of dmesg and content of /var/log/dmesg? |
1,394,071,337,000 |
I want to synchronize processes based on lock files (/ socket files). These files should only be removable by their creator user.
There are plenty of choices:
/dev/shm
/var/lock
/run/lock
/run/user/<UID>
/tmp
What's the best location for this purpose? And what way are above locations meant to be used for?
|
/dev/shm : It is nothing but implementation of traditional shared memory concept. It is an efficient means of passing data between programs. One program will create a memory portion, which other processes (if permitted) can access. This will result into speeding up things.
/run/lock (formerly /var/lock) contains lock files, i.e. files indicating that a shared device or other system resource is in use and containing the identity of the process (PID) using it; this allows other processes to properly coordinate access to the shared device.
/tmp : is the location for temporary files as defined in the Filesystem Hierarchy Standard, which is followed by almost all Unix and Linux distributions. Since RAM is significantly faster than disk storage, you can use /dev/shm instead of /tmp for the performance boost, if your process is I/O intensive and extensively uses temporary files.
/run/user/$uid: is created by pam_systemd and used for storing files used by running processes for that user.
Coming to your question, you can definitely use /run/lock directory to store your lock file.
| Linux file hierarchy - what's the best location to store lockfiles? |
1,394,071,337,000 |
I'm using Debian testing without any problems for ~6 years (I'm just regularly updating it), but recently it started to show a random behaviour that can be summarized as "Low I/O performance which persists until reboot".
The problem is, suddenly all disk reads and writes slow down to ~5MB/sec which results in continuous read and writes. Since the rate is so low, disks are not mechanically challenged or stressed, but everything slows down until I reboot.
I/O subsystem of the computer consists of one OCZ Vertex 3 SSD and two WD Caviar Black HDDs. SSD holds read-heavy part of the OS and a partition on the HDD holds the rest.
To diagnose the problem I tried the following without success:
top doesn't show any runaway activity neither in CPU nor I/O usage.
hdparm returns normal performance ratings of the disks (I only checked -t though).
smartctl doesn't show any performance problems in disks. Long tests showed that the disks are as good as new.
System has Z77 Chipset, 16GB of RAM and Intel i7 3770K CPU and the stats show no signs of saturation in RAM, I/O or CPU, but I'm not experienced to debug problems like this (esp. in kernel space). Any help will be appreciated.
Update 1:
I ran (forced) fsck on every partition as a precaution. All FS are clean.
Incidentally I found a BIOS upgrade which came out a month ago & applied it.
No partition is filled more than 50%.
Update 2:
The problem is not surfacing up for two days. Either fsck or the BIOS update cleaned some clogs in the system. I'm still monitoring the issue and will close the question with a post-mortem answer.
Update 3:
Problem just resurfaced and I did some more digging. Please see the answer.
|
I managed to reproduce the problem again and it was result of a big disk cache. My disk caches can grow more than 8GB and seems that some applications doesn't like it and I/O suffers.
Dropping disk caches with echo 3 > /proc/sys/vm/drop_caches as root remedies the problem. I currently don't know why large disk caches causes this I/O degradation.
Last Update: After more investigation I've found out that number of files in the cache was triggering the problem. It was trashing the disks while trying to commit many small files back to the disk. Since I was using the system for ten years, I've took the plunge and reinstalled with 64 bit Debian. Now it's working smoothly. It was probably a side effect of ten years of upgrading with finding limits of 32 bit operating system.
| Massive, unpredictable I/O performance drop in Linux |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.