Lnx Flashcards

(170 cards)

1
Q

Remote command execution

Linux: How to run a command on a remote machine.

A

Use ssh,

> ssh  laeeq@192.168.0.49    ls  /tmp
> ssh  laeeq@192.168.0.49    date

you may have to give absolute path of the command you want to execute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

tcpdump

What is tcpdump command to get traffic to/from port 3000

A
>  tcpdump -i any port 3000
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

vimdiff

What are vimdiff commands?

A
  • CTL-ww swhitches windows
  • do: diff obtain, get difference from other window
  • dp: diff put: send difference to other window
  • ]c: go to next diff
  • [c: go to previous diff
  • zo: open zip
  • zc: close zip
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

core file

How to force core file generation from a crashing program.

A
> ulimit   -c  unlimited
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to display current resource limits for a user?

A
> ulimit    -a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

gdb

How to set a conditional break point in gdb.

A
b  fileName.c:56  if x==50
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Dangling symbolic links

What happens when you delete a symbolic link.

A

The target or actual file remains unaffected.
However, if u delete the target, the symbolic link continues to point to non-existing target file (this called dangling/orphaned symbolic links).

Soft link = Symbolic link

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what does the tee command do?

A

tee cmd is used to copy the output of a command to a file.

In addition to displaying normal output of the command, the output is also written to a file.

It is used with pipe symbol

> wc -l   prog.c   |   tee    file1.txt

to append to a file instead of overwriting,

> wc -l  prog.c   |   tee -a   file1.txt
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How is HereDocument used?

A

When a large amount of textual multiline data is needed as argument to a command, we can use Here Docuement and provide data inside shell script itself, rather than providing data in a file.

cat << ABCD
line 1111
line 222
line 333
ABCD
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Pass envirenment variable to a script

How to make a variable available inside a shell script?

A
> TARGET=x86       ./script.sh

Value of TARGET will be available inside script.sh

Assign values to env variables just before calling the script on the same line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to read a variable inside a shell script from keyboard?

A

Use read command,

read    variableName
echo    $variableName
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a common usage of xargs?

A

When a command generates a list of files, such as find command. We can make this file list available to another command like grep or rm etc, so that these commands can work on the files list generated by the first command.

Following can be used to delete all header files found by cmd find

> find   .   -name   "*.h"  |  xargs  rm  -v

args is normally used after a pipe symbol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Errors in make file recipes

In make file what happens when an error occurs at any time?

A

Default behaviour: Make program is aborts immediately, no further commands are executed.

If you pre-append minus sign ‘-‘ to any command, error in that command will be ignored and next command will be executed.

If you pre-append ‘@’ to any command, make will not print that command before executing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are common automatic variables in makefiles?

A
  • $@ : Name of current target.
  • $^ : List of all dependencies
  • $< : First dependency in the list of dependencies.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

gdb: How to get the sequence of function calls leading to current point of execution?

A
bt
backtrace

Each stack frame will have a number associated with it. Top most stack frame is the most recent one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

gdb: How to get the local variables in current function?

A
info  locals
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Command line editing: Go to begining of line.

A
CTL  a

a = begining

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Command line editing: Go to end of line.

A
CTL  e

e = end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Command line editing

Command line editing: Delete from curser positionn to the end of line?

A
CTL  k

k = Kill

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Command line editing

Command line editing: Clear the whole current line

A
CTL ak

ak = All Kill

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

iptables: name three chains

A

INPUT chain, OUTPUT chain, FORWARD chain

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is an iptables policy?

A

Each chain has a policy, ACCEPT or DROP.

ACCEPT: Allow all pkts unless a specific rule forbids that kind of pkt.

DROP: Disallow all pkts unless a specific rule allows that kind of pkt.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are primary and secondary groups in Linux?

A

Primary group: Has the same name as user name. Created at the time when user is created. Newly created user has membership of this group immediately.

Secondary group: Other groups created separately. Users need to be made members of secondary groups explictly using cmd gpasswd

> gpasswd     groupName    -a     userName
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Linux user groups

How to find to which groups a user belongs to?

A
>  groups         laeeq
>  groups           # will give info about current user.

You can also use,

~~~

> id laeeq
id # Lists groups which logged in user is member of
```

You can also read /etc/group file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Which file contains group information
/etc/group
26
How to create a new group in Linux?
``` addgroup newGroupName # Ubuntu etc groupadd newGroupName # Redhat etc ``` ## Footnote Verify using `cat /etc/group`
27
# Add a user to a Linux group How to make user1 a member of group1
Use command gpasswd `gpasswd group1 -a user1` ## Footnote You can also use `usermod` command.
28
# Revoke the membership from a group How to remove a user from a group? ## Footnote User will no longer have that group's permissions
`gpasswd groupName -d userName` ## Footnote Verify using `groups userName`
29
# Linux user groups How to modify a groups details, like change group name etc.
Use command `groupmod` ## Footnote Modify group
30
How is the owner group of a file determined?
Owner group of a file is the **primary group of the user who created the file**
31
# Linux gropus What are `system` & `non-system` of groups in Linux?
There are two kind of groups, 1. non-system groups 2. system gropus Non-system groups are used for managing user permissions and access. System groups are used by system services & daemons to allow system processes to share access to resources, files, directories etc. non-system group gid is normally greater than 1000. System group gid is normally less than 1000.
32
# system groups How to create a **system group** in Linux?
``` addgroup newGroupName --system ``` ## Footnote Normally group id (gid) is less then 1000 for these groups
33
# Linux system users How to create a system user?
``` > adduser newUserName --system ``` ## Footnote * Normally UID of system users is less than 1000. * They may not have home dir. * They may not have human login capability.
34
# Linux directory permissions How to interpret the permissions of a directory as opposed to a file? | as opposed to a permissions of a file.
* **read:** Ability to list dir contents * **write:** Ability to create/delete files in this dir. * **execute:** Ability to cd into this dir.
35
# setuid What is the purpose of setuid on an executable file?
When you set the `setuid` on an executable file, then when that file is executed by a non-owner user, the resulting process will still have all permissions of the real owner of that file. Even though the real owner did not run that program. ## Footnote -rwS Capital S means, original file did not have execute permission. lower case s means, original file had execute permission too.
36
How to set sticky bit on a file?
``` chmod +t fileName ``` ## Footnote other's permission will become --T
37
# Linux groups How to change the owner group of a file?
Use `chgrp` command ``` > chgrp groupName fileName ```
38
# Linux groups How to change the owner group of a file?
Use `chgrp` command, ``` chgrp groupName fileName ```
39
# C++ scoped enum What are scoped enums in C++
Define like this, ``` enum class Fruit { banana, apple, }; Fruit frt; frt = Fruit::apple; ```
40
What is the benefit of curly brace initialization of variables, like ``` int x{10}; // Rather than, int x = 10; // or int x(10); ```
Compiler enforces exact type match. ``` int x = 5.1; // works int y(6.2); // works // but int z{7.3}; // compilation error ``` ## Footnote A conversion from floating point to integer is not done at initialization.
41
# Ubuntu packages How to list all ubuntu packages?
``` > apt list > apt list --installed ``` ## Footnote Use grep for specific pkg
42
How to un-install an ubuntu package?
``` > apt remove pwgen # Does not remove config files > apt purge pwgen # Removes all config files ```
43
How to remove unnecessary dependencies from Ubuntu?
``` > apt autoremove ```
44
How to check if a specific pkg is installed on ubuntu system?
``` > apt search pwgen ``` ## Footnote If it is insalled, it will show `[installed]`
45
How to `autoclean` old downloaded archive files in `ubuntu`?
``` > apt autoclean ```
46
How to get information about an `ubuntu` package liks `pwgen`?
``` > apt show pwgen ``` ## Footnote *Does not show if a pkg is installed*. Use `apt list pwgen` for that.
47
Does each ubuntu release have a `codename`?
Yes, use following command, ``` > lsb_release -a ``` ## Footnote Examples are `jammy`, `Bionic Bever`, `Focal Fossa` etc.
48
How to create netcat chat between two computers?
Create listner/server ``` > nc -l -p 1299 # -l for listen, -p port num ``` Create netcat client, ``` > nc 192.168.1.100 1299 # dont use -p on listener ```
49
How to check if a port is open on a machine using `telnet`
``` > telnet 192.168.1.100 22 ``` * connected to 192.168.1.100 ==> Open * Trying 192.168.1.100...... ==> Not open More examples, ``` > telnet google.com 443 ``` ## Footnote * telnet google.com 443
50
On Redhat Linux, how do you list `package groups`
``` > dnf group list > dnf group list --hidden > dnf group list --installed ```
51
How to install `Development Tools` in RHEL?
``` > dnf groupinstall "Development Tools" ```
52
In Redhat linux, how to get info about a `package group`?
``` > dnf group info "Development Tools" ```
53
How to check the status of network manager?
``` > systemctl status NetworkManager > nmcli general ``` ## Footnote Do `double tab` after each part to see options available
54
| How to get info about NICs?
``` > nmcli device status > nmcli device show > nmcli device show eth0 > nmcli connection show > nmcli connection show eth0 ```
55
How to easily create a new network profile in Linux.
* Go to network settings (Wired) * Locate the interface name you want to use, press `+` * Add details such as DNS etc. * To activate new profile, disconnect networking, and connect using new profile.
56
What are the major components of a `connection profile`?
* interface name (eth0, enp3s0) * profile name (user defined text) * Type (ethernet, wireless) * IP4 address * subnet mask * Default gateway (gw4) * DNS addresses
57
How to create a connection profile using `nmcli` command?
``` > nmcli connection add type ethernet ifname eth0 con-name my_new_conn ip4 192.168.1.111/24 gw4 192.168j.1.1 ``` Specify following parameters, * connection type (ethernet / radio) * NIC name (eth0, enp7s0) * New profile name (my_new_conn) * ip4 (192.168.1.111/24) * Default gateway (192.168.1.1)
58
How to activate an already created connection profile?
``` > nmcli connection up my_conn_profile_1 ```
59
How to de-activate an active connection profile?
``` > nmcli connection down my_conn_profile_1 ```
60
How do you modify the parameters of a network profile? ## Footnote e.g., add a DNS address.
``` > nmcli connection modify my_connection ipv4.dns "8.8.8.8 8.8.4.4" > nmcli connection modify my_connection ipv4.address "192.168.1.100/24" > nmcli connection modify my_connection ipv4.gateway "192.168.1.1" ``` ## Footnote Take network profile down and up again to take effect.
61
How to make output of `nmcli` cmd more readable?
Use `-p pretty` option, ``` nmcli -p connetion show ``` ## Footnote Use `-p` with all nmcli operations.
62
How to restrict a network profile usage to a set of users?
``` > nmcli con mod my_connection connection.permissions mujid > nmcli con mod my_connection connection.permissions user:mujid,farooq ```
63
How do you delete a network/connection profile?
``` > nmcli connection delete my_connection_profile ``` ## Footnote Use `nmcli connection show` to list all known connections/profiles.
64
| While entering `nmcli` command, how can you get help while typing?
By pressing TAB twice.
65
What are some common DNS addresses?
* 75.75.75.75 * 75.75.76.76 * 8.8.8.8 * 8.8.4.4
66
How to get `overall` info about all NIC cards in a Linux system?
``` > nmcli device status ``` ## Footnote This is the first command you type. From here, you can drill down further using `nmcli device show eth0` etc.
67
In `nmcli` lingo, what is another name for a `profile`?
`connection name` or `con-name` ## Footnote connection name or profile name is listed as `CONNECTION` in last column of , `nmcli device status`
68
When creating/adding a new connection profile using `nmcli`, what are the first three parameters?
**con-name, type, ifname** * ifname (an existing NIC name, u can get it by `> mcli device status`) * profile name/connection name: A text name you choose. * type (ethernet, wifi etc) ## Footnote `> nmcli connection add type ethernet con-name my_new_profile ifname enp3s0`
69
When you create a file using `touch` commmand, does it have execute permissions by anybody?
**NO** By default, when you create a file, it does not have execute permissions by user, group or others. You can of course give execute permissions later using `chmod` command.
70
What is the role of `umask`
When you create a file, the bits in `umask` are *removed* from just created file. E.g., umask=0002 will make sure `others` don't have write permissions to created files. umask=0333 will make sure that newly created files will have only read permissions by everybody.
71
How to find current `umask` value?
``` > umask ``` ## Footnote likely output is 0002, this will remove write permission for `others` on newly created files.
72
How to make `umask` equal to 0333
``` > umask 0333 ``` ## Footnote This will make sure newly created files have only read permissions by everybody. -r--r--r--
73
How to find what the permissions on a newly created file be, with currently set value of `umask`
``` umask -S ```
74
How to list all services/units by `systemd`
``` > systemctl list-units > systemctl list-units --type=service > systemctl list-units --all > systemctl list-unit-files > systemctl list-unit-files | grep NetworkManager ```
75
How to find all journal entries related to a service/unit
``` > journalctl -u NetworkManager > journalctl -u ssh -f # follow similar to tail -f ```
76
How to view a systemd service's configuration file?
``` > systemctl cat NetworkManager ``` ## Footnote `cat /etc/systemd/system/NetworkManager.service`
77
How to list dependencies of a systemd service?
``` systemctl list-dependencies NetowrkManager systemctl list-dependencies --all NetworkManager ```
78
How to get low level details about a systemd service?
``` > systemctl show NetworkManager ```
79
After modifying a systemd service, how to reload systemd process to pickup modifications?
``` > systemctl daemon-reload ```
80
What is the basic format of a systemd service file?
``` cat /etc/systemd/system/test.service [Unit] Description=Example systemd service unit file. [Service] ExecStart=/bin/bash /usr/sbin/example.sh [Install] WantedBy=multi-user.target ```
81
What is the equivalent of `system V run-levels` in `systemd`?
**Targets**
82
Where should you keep your service files?
in **/etc/systemd/system**
83
How to list all `systemd` targets?
``` > systemctl list-units --type=target ```
84
Name some `systemd` targets
* multi-user.target * network-online.target * rescue.target * graphical.target
85
How to find default `systemd` target, that system tries to reach after booting?
``` > systemctl get-default ```
86
How to enforce strict ordering of `systemd` service starting?
By using `Before` and `After` in service file. ## Footnote `wants` and `requires` are not strict.
87
What are the things that `systemd` manages?
**units** Some unit types are, * services * timers * mounts
88
How do `systemd` timers work? ## Footnote timer is a kind of unit that systemd manages apart from services.
* You create a unit file `abc.timer`. * Specify periodicity in this file * You create a service file `abc.service` * You start timer unit * Now abc.service will be started periodically as per timer period. ## Footnote *timer unit file has same name as service file*
89
How do you create an infinite loop in a bash script?
``` while true do echo "Test - 1" sleep 1 done ```
90
| In Linux, how to nicely display an XML file?
``` > xmllint --format abc.xml ``` | ```
91
How to kill all processes run by a user hamid?
``` > sudo killall -u hamid ```
92
How to create a (normal) user in Linux?
``` > sudo adduser hamid ``` You can leave fields like room/phone etc blank. ## Footnote You can login as this user by doing ``` > su - hamid ```
93
How to create a Linux user and make his login shell `rbash`
``` > sudo adduser hamid --shell /bin/rbash ```
94
In Linux, how to find user-id and group-id of a user?
``` > id # gives info about logged in user > id hamid # info about another user ``` ## Footnote Default values are taken from `/etc/adduser.conf` file.
95
How to remove a Linux user?
Ubuntu ``` > sudo deluser hamid # home dir wont be deleted > sudo deluser hamid --remove-home > sudo deluser hamid --remove-all-files ``` Redhat may not have `deluser` cmd. Use `userdel` ``` > userdel hamid > userdel -r hamid # remove home-dir etc ```
96
How to become root user in Linux?
``` > sudo su - ```
97
How to check ACL permissions for a file?
# file: youtube/ ``` > getfacl fileName.txt ``` Typical output ``` owner: root # group: root user::rwx user:user1:rwx group::r-x mask::rwx other::r-x ```
98
How to give ACL permissions "rwx" for user `hamid` for a specific file?
``` > setfacl -m u:hamid:rwx fileName.txt ```
99
How do you check if a file has ACL permissions associated with it?
Normal files have only -rwxrwxrwx permissions. But a file with ACL permissions also has a "+" symbo at the end, like -rwxrwxrwx+
100
How to revoke some ACL permissions for a user or group?
Set new permissions explicitly. For removing write permissions for a user on a file, ``` > setfacl -m -u:hamid:r-x fileName.txt ```
101
How to find details of a `Linux` distribution?
``` > lsb_release -a > ls /etc/*rel* > cat /etc/lsb-release > cat /etc/os-release ```
102
What are some `systemd` directives to start programs
``` ExecStart /full/pathname/of/binary ExecStartPost /bin/bash /path/name/script.bash ExecStartPre /bin/bash /fullPath/script.bash ExecStop /bin/bash /full/path/endingScript.sh ``` * ExecStartPost starts the program immediately after starting the main program. NOT after main program finishes.
103
When does systemd service directive `ExecStop` take effect?
**Upon graceful shutdown of servcie.** * When you stop service using `systemctl stop svcName` * When the main program normally finishes It DOES NOT run when the service crashes due to signal etc.
104
How can I restart a systemd service after a crash, e.g., when underlying process receives a signal (9).
Use `Restart=on-failure` ``` [Unit] Description = A demo service [Service] ExecStart = /bin/bash /path/to/script.bash Restart=on-failure RestartSec=30s # waits of 30 sec before restarting. ``` ## Footnote Google: Setup self-healing services with systemd
105
What is the `id` of `super user` in Linux?
**0, zero** uid=0(root) gid=0(root) ## Footnote Use command `id` to get user identifier.
106
How to delete a group in Linux?
``` > groupdel groupName ``` ## Footnote All group names are listed in `/etc/group` This file has one line for each group. That line also contains all users belonging to this group.
107
In RedHat Linux, what is group `wheel`?
In RHEL, `wheel` is the name of a group. All members of this group have `sudo` capability. If you want to give `sudo` capability to any user, just add him to group wheel. ``` > gpasswd wheel -a hamid # hamid can now do sudo > gpasswd wheel -d hamid # hamid cannot do sudo ``` In `Ubuntu` this kind of group is named `sudo`
108
In Redhat Linux, how do you list packages?
``` > dnf list > dnf list installed > dnf list | grep tmux > dnf list installed | grep tmux ```
109
How to find which `systemd` units have failed?
``` > systemctl --failed > systemctl --failed --all ```
110
What Linux cmd is used to get info about power sources to the board?
``` > upower --enumerate > upower -d ```
111
How the cmd `pstree` works?
``` > pstree > pstree - u user1 > pstree -p -u hamid # with PIDs ``` ## Footnote Login with `su - hamid` for cleaner outputs.
112
How are threads shown in `pstree` cmd output?
{} means threads of a process ``` |--2*{thread} ``` The process has 2 threads running at the momemnt.
113
How does `pstree` show, when `a.out` spawns two threads?
``` pstree -u hamid bash ---a.out---2*{a.out} Default compact format ``` ``` pstree hamid -c --a.out-------{a.out} | ---{a.out} Non-compact format, each thread in its own line. ``` ``` pstree hamid -T --a.out-------{a.out} No thread information ```
114
How to find parents of a process with `pstree` cmd?
Fisrt find PID with `pstree hamid -p -c` Then find parents using `-s` option ``` > pstree -s 1234 > pstree -s -p 1234 ``` ***Don't*** use username (hamid) with above cmds
115
In Linux, how to print all `environment variables`?
* `env` cmd gives only `exported` variables * `set` cmd gives `exported` as well as `un-exported` variables. * `set` cmd gives more variables. * `env` output is a subset of `set` output
116
# m How to `unset` a variable in `bash`?
``` > unset VarName ```
117
How to get the value of a shell variable?
``` echo $VarName echo ${VarName} # better way ``` Using curly braces {} is always better
118
How is `alias` cmd used in Linux?
``` > alias cl=clear > unalias cl # remove alias ```
119
How to create exported shell variables for **all users** in Linux?
Declare them in `/etc/environment` file.
120
How to use `CTL R` interactive history?
* Keep pressing `CTL R` to keep going back. * Press left or right arrow key to copy currently displayed cmd to cmd-line. You can edit this cmd now. * Press `CTL S` to go forward. * If going forward with `CTL S` doesn't work, type `stty -ixon`
121
What are some important shell variables?
* $USER * $HOME * $SHELL * $PWD *$UID * $HOSTNAME * $PS1, $PS4
122
How to get details about a process, given its PID?
``` > ps -f 1234 > ps -ef # all processes > ps -ef | grep cmdName ```
123
How to find the exit status of last command?
Use `$?` 0 means success, 1 means failure. Try `true` and `false` cmds. Then do `$?` ``` > true > echo $? # should print 0 > false > echo $? # should print 1 ```
124
Give some example usages of `test` cmd in bash scripts.
``` test 1 -eq 1 # $? = 0 test 1 -gt 2 # $? = 1 false test 1 -eq 1 -a 2 -gt 1 # -a = AND, -o = OR test -f fileName test -d dirName ``` ## Footnote Using single or double square brackets is more convenient. [], [[]]
125
In shell scripts, how to test conditions using single square brackets?
``` [ 1 -eq 1 ] # $? = 0 [ ! 1 -eq 1 ] # $? = 1 false [ -f fileName ] [ ! -d dirName ] # return 0 if dirName is not a directory ``` ## Footnote If you use double brackets, you can use ==, >, < instead of -eq, -gt, -lt
126
In bash scripting, how is double square bracket method different from single square bracket method?
Difference is in condition representation. With single sqr brkt, you use `-eq, -lt, -gt, -a, -o` etc for comparision. With double sqr brkt, you can use usual algebraic symbols `==, >, < &&, ||` for comparision.
127
How to check if a user by name `hamid` exists in Linux?
Use `id` command ``` > id hamid ```
128
How to check if `ubuntu` has a specific package installed?
``` > apt search pwgen ``` Output should have `[installed]` in it.
129
In `ubuntu` where is the info about repositories?
* /etc/apt/sources.list * /etc/apt/sources.list.d Each line represents one repository, or package source. A repository line can be commented out by `#` in the begining.
130
Give an example of arithmatic operation in shell script using double parenthesis.
``` a=$(( 3 + 5 - 2)) echo $a # 6 a= $(( 2**10)) # 1024 ``` * No floating point arithmetic * Don't use $ sign with variables inside double paranthesis.
131
How is `bc` used to perform floating point arithmetic in shell scripts?
``` echo "1.5 + 2.7" | bc # 4.2 echo "scale=2; 1/3" | bc # .33 a=.5 b=$( echo "$a + 0.3) echo $b #.8 ```
132
What is the meaning of ``` const int *ptr; ```
``` const int *ptr; ``` * `ptr` points to an integer * `ptr` cannot be used to modify the integer it is pointing to. * `*ptr` cannot appear on the LHS of `=` * While `ptr` cannot change the object it is pointing to, `ptr` itself can be changed to point to different objects. ``` int x=5, y = 10; const int *ptr; ptr = &x; ptr = &y; // Both valid *ptr = 20; // This is wrong ``` It is *not* necessary to initialize ptr to some integer at the time of declaration.
133
What the meaning of following, ``` int x=10, y=20; int * const ptr = &x; ```
* `ptr` points to an integer `x` * `ptr` cannot point to any other integer * `ptr` can be used to modify the value of integer it is pointing to. ``` *ptr = 25; // is valid. Value of x is now 25 ptr = &y; // Not valid. ptr cannot point to other integers. ``` `ptr` must be initialized to point to an integer at the time of declaration. ``` int * const ptr; // Invalid, ptr must point to some int at the time of declaration. ```
134
What is the meaning of ``` int x=10, y=20; const int * const ptr = &x; ```
* `ptr` is pointing to an integer * `ptr` cannot point to any other integer * `ptr` cannot be used to modify the value of integer ptr is pointing to. * Neither `ptr` nor `*ptr` can appear on LHS of `=1
135
What is a `mutable` member variable in a C++ class?
A `mutable` member variable can be modified inside a `const` function.
136
What is C++11 way of forcing the compiler to generate a default Xtor, even though, the class already has non-default Xtors?
``` class A { public: A(int x); // Non default xtor A() = default; // Compiler generated }; ```
137
How to delete/remove a docker image?
``` docker rmi image_id ```
138
How to list all docker containers?
``` > docker container ls # only running containers > docker container ls -a # whether running or not running ```
139
How to start/stop an already existing container
``` > docker start abcd > docker stop abcd ```
140
How to go inside a running container? ## Footnote Attaching to a container
``` docker exec -it abcdef bash ``` ## Footnote abcdef should be started first with `docker start abcdef`
141
How to create a docker container and go inside it from an image?
``` > docker run -it img_name bash // Following will give container a name > docker run -it --name khan_container alpine ash // Run container in detached mode > docker run -dit alpine ash ```
142
How to list all docker images on my local machine?
``` > docker image ls ```
143
How to run a cmd on a running container and get the output? ## Footnote Don't want to go inside the container.
``` > docker exec container_id cmd_name ``` ## Footnote Note there is no `-it` in command, since we don't want interactive.
144
How to create a docker image from a `Dockerfile`? ## Footnote `Dockerfile` is in the current directory.
``` > docker build -t newImageName . ``` ## Footnote `Dockerfile` must be in the current direcotry
145
How to get details about a docker container?
``` docker inspect container_id ``` Following info is available in JSON object * Status (exited, running, ...) * Running (false, true) * Image (sha256) * NetworkSettings: Networks:IPAddress
146
Alpine Linux: How to add packages
Use `apk` ``` > apk update > apk add pwgen ```
147
How to create a docker container in detached mode from a given image_id?
``` > docker run -dit alpine ash // To go inside this container > docker attach container_id // To detach from this container, press CTL p q ```
148
How to list all available docker networks?
``` > docker network ls ``` Default network for a container is `bridge`
149
How to see which docker containers are connected to the `bridge` network?
``` > docker network inspect bridge ``` containers: {Name..., IP4Address...} .... "IPAM"."Config"."Subnet" contains the subnet address which all attached containers will have.
150
Docker: How to create a new `bridge` type network?
``` > docker network create --driver bridge khan_bridge_nw_1 > docker network inspect khan_bridge_nw_1 // To delete this network, > docker network rm khan_bridge_nw_1 // To create a container connected to this netowrk, > docker run -it --network khan_bridge_nw1 alpine ash ```
151
How to ping a machine only 5 times?
``` > ping -c 5 192.168.0.100 ``` statistics will be printed after 5 pings.
152
How to connect an already running container to a docker network?
``` > docker network connect khan_nw_1 container_id ``` ## Footnote At the time of creation of container, it can be connected to only one network. Later it can be connected to any number of networks using this method. One network at a time.
153
What is the difference between `docker run` and `docker exec` cmds?
* `docker run` takes an image_id as a parameter & creates & run a new container * `docker exed` takes container_id of an existing container. Examples, ``` > docker run -it ubuntu /bin/bash > docker exec -it sad_khan /bin/bash ```
154
How to create a docker image from an existing container along with all its current data?
``` > docker commit container_id new_img_id ```
155
At what state in a container's lifetime, is port mapping done?
Port mapping is done when creating the container from the image (with `docker run -p 80:80` cmd. Once a container is created, we cannot map more ports to an existing container. A new container from the image will need to be created. | Port mapping is done with `docker run` cmd, NOT with `docker exec` com
156
What is `upcasting` in C++
When we declare a pointer to Base class, and make it point to a Derived class object. It is always allowed in public inheritance. Only Base class members can be accessed this way. Additional Derived class members cannot be accessed this way. `Object slicing` is involved here. We are making a Derived class object `pretend` as if it is a Base class object. It is always safe.
157
What is `downcasting` in C++
When we make a Base class object pretend as if it is indeed a Derived class object. Accessing additional derived class members (which are non-existant in Base class obj) will result in unpredictable behaviour. Compilation will go through but run time behaviour will be unpredictable. We declare a pointer to Derived class and make it point to a Base class object by explicit type-casting. ``` Derived *ptrD; Base b; // Base class object ptrD = (Derived *) b; ``` It is dangerous.
158
In `C++` what is `lambda introducer`?
`lambda introducer` is the square brackets just after `=` and before the round brkts in lambda definition. ``` auto greet = []() { cout << "Hello from lambda\n"; }; ``` in above exmpl `[]` is the `lambda introducer.
159
What is `lvalue` and `rvalue` in C++?
lvalue is a variable with address like `int x` rvalue is a temporary value or literal that appears in an expression, like ``` x = 17; // 17 is rvalue x = a + b; // a + b is rvalue ``` rvalues don't have an address and can only appear on RHS. When a function returns value `by value`, it is an rvalue, and cannot appear on LHS. when a function returns value `by reference` it is an lvalue and can appear on LHS.
160
What's the correct name for old C++ reference variable.
lvalue reference.
161
What is a `const reference` in C++?
It is a constant reference to an existing variable. It can be used to read the variable, but not to modify it. ``` int x = 100; const int& cref = x; // cref is a constant reference cout << cref << endl; // good, only reading. crfef = 20; // compile error, cannot modify ``` const reference can also be used with literal values, ``` const int& k = 50; // works fine ```
162
How to define an `rvalue reference` in C++?
By using `&&` ``` int&& rref = 50; rref = 100; // Allowed ```
163
How is a `unique pointer` to an integer created in C++?
``` unique_ptr up1( new int(17) ); ``` Create a raw pointer at the same time you create the unique pointer and pass the raw pointer to the constructor. Unique pointers cannot be copied to other unique pointers, that's a compilation error. There destructor gets called automatically when they go out of scope.
164
How is a unique pointer to an integer created using `make_unique` template function?
``` unique_ptr uptr1 = make_unique(42); ``` In last round brackets, give all Xtor parameters.
165
How to release memory held by unique_ptr?
``` // uptr is a unique pointer, uptr.reset(); // uptr is now NULL, destructor will be called. // Get the underlying raw/classical pointer, int *rawPtr = uptr.release(); // uptr is now NULL // rawPtr holds the classical pointer to the object. // You can now `delete` it. ```
166
How is a shared pointer created?
``` shared_ptr sp1 = make_shared(25); shared_ptr sp2(new int(47)); ``` Shared pointers can be copied to each other. You can use reset() to delete the object. Shared pointers can be passed to functions.
167
What is a `weak pointer` in C++?
A weak_ptr is a non-owning pointer. It is assigned a value from a `shared_ptr`. Weak pointer cannot be dereferenced directly using a `*`. They have tod be locked first to make sure they are not dangling.
168
What is the use of `explicit` in C++?
In C++, `explicit` is used to prevent type conversion introduced by single parameter constructors. ``` ClassName obj = 35; // Implicit type conversion from int to ClassName. ``` `explicit` is used to prevent inadvertant type conversion.
169
How do `public, private, protected` access specifiers work in C++ classes?
* `public` members can be accessed from anywhere. * `private` members can only be accessed from within the methods of the class. They *cannot* be accessed from derived class implementation code. * `protected` members can only be accessed from within the methods of the class *and also from the methods of derived classes*. A good guideline is, * All members can be accessed from anywhere within the implementation code for that class. * All `public` members can be accessed from anywhere. * In a derived class, the protected members of parents are NOT accessible.
170
In `C++` what is a `Pure Abstract Class` (PAC)?
A `Pure Abstract Class` has * No data members * No concrete functions/methods (all pure virtual) A `PAC` provides no implementation, only API interface definitions.